blob: 9ba414031204c35f62fb7dcf7821caf182cea8eb [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
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700257
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258// --- InputReader ---
259
260InputReader::InputReader(const sp<EventHubInterface>& eventHub,
261 const sp<InputReaderPolicyInterface>& policy,
262 const sp<InputListenerInterface>& listener) :
263 mContext(this), mEventHub(eventHub), mPolicy(policy),
264 mGlobalMetaState(0), mGeneration(1),
265 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
266 mConfigurationChangesToRefresh(0) {
267 mQueuedListener = new QueuedInputListener(listener);
268
269 { // acquire lock
270 AutoMutex _l(mLock);
271
272 refreshConfigurationLocked(0);
273 updateGlobalMetaStateLocked();
274 } // release lock
275}
276
277InputReader::~InputReader() {
278 for (size_t i = 0; i < mDevices.size(); i++) {
279 delete mDevices.valueAt(i);
280 }
281}
282
283void InputReader::loopOnce() {
284 int32_t oldGeneration;
285 int32_t timeoutMillis;
286 bool inputDevicesChanged = false;
287 Vector<InputDeviceInfo> inputDevices;
288 { // acquire lock
289 AutoMutex _l(mLock);
290
291 oldGeneration = mGeneration;
292 timeoutMillis = -1;
293
294 uint32_t changes = mConfigurationChangesToRefresh;
295 if (changes) {
296 mConfigurationChangesToRefresh = 0;
297 timeoutMillis = 0;
298 refreshConfigurationLocked(changes);
299 } else if (mNextTimeout != LLONG_MAX) {
300 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
301 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
302 }
303 } // release lock
304
305 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
306
307 { // acquire lock
308 AutoMutex _l(mLock);
309 mReaderIsAliveCondition.broadcast();
310
311 if (count) {
312 processEventsLocked(mEventBuffer, count);
313 }
314
315 if (mNextTimeout != LLONG_MAX) {
316 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
317 if (now >= mNextTimeout) {
318#if DEBUG_RAW_EVENTS
319 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
320#endif
321 mNextTimeout = LLONG_MAX;
322 timeoutExpiredLocked(now);
323 }
324 }
325
326 if (oldGeneration != mGeneration) {
327 inputDevicesChanged = true;
328 getInputDevicesLocked(inputDevices);
329 }
330 } // release lock
331
332 // Send out a message that the describes the changed input devices.
333 if (inputDevicesChanged) {
334 mPolicy->notifyInputDevicesChanged(inputDevices);
335 }
336
337 // Flush queued events out to the listener.
338 // This must happen outside of the lock because the listener could potentially call
339 // back into the InputReader's methods, such as getScanCodeState, or become blocked
340 // on another thread similarly waiting to acquire the InputReader lock thereby
341 // resulting in a deadlock. This situation is actually quite plausible because the
342 // listener is actually the input dispatcher, which calls into the window manager,
343 // which occasionally calls into the input reader.
344 mQueuedListener->flush();
345}
346
347void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
348 for (const RawEvent* rawEvent = rawEvents; count;) {
349 int32_t type = rawEvent->type;
350 size_t batchSize = 1;
351 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
352 int32_t deviceId = rawEvent->deviceId;
353 while (batchSize < count) {
354 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
355 || rawEvent[batchSize].deviceId != deviceId) {
356 break;
357 }
358 batchSize += 1;
359 }
360#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700361 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362#endif
363 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
364 } else {
365 switch (rawEvent->type) {
366 case EventHubInterface::DEVICE_ADDED:
367 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
368 break;
369 case EventHubInterface::DEVICE_REMOVED:
370 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::FINISHED_DEVICE_SCAN:
373 handleConfigurationChangedLocked(rawEvent->when);
374 break;
375 default:
376 ALOG_ASSERT(false); // can't happen
377 break;
378 }
379 }
380 count -= batchSize;
381 rawEvent += batchSize;
382 }
383}
384
385void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
386 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
387 if (deviceIndex >= 0) {
388 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
389 return;
390 }
391
392 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
393 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
394 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
395
396 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
397 device->configure(when, &mConfig, 0);
398 device->reset(when);
399
400 if (device->isIgnored()) {
401 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100402 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 } else {
404 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100405 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 }
407
408 mDevices.add(deviceId, device);
409 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700410
411 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
412 notifyExternalStylusPresenceChanged();
413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414}
415
416void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700417 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
419 if (deviceIndex < 0) {
420 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
421 return;
422 }
423
424 device = mDevices.valueAt(deviceIndex);
425 mDevices.removeItemsAt(deviceIndex, 1);
426 bumpGenerationLocked();
427
428 if (device->isIgnored()) {
429 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100430 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 } else {
432 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100433 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 }
435
Michael Wright842500e2015-03-13 17:32:02 -0700436 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
437 notifyExternalStylusPresenceChanged();
438 }
439
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 device->reset(when);
441 delete device;
442}
443
444InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
445 const InputDeviceIdentifier& identifier, uint32_t classes) {
446 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
447 controllerNumber, identifier, classes);
448
449 // External devices.
450 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
451 device->setExternal(true);
452 }
453
Tim Kilbourn063ff532015-04-08 10:26:18 -0700454 // Devices with mics.
455 if (classes & INPUT_DEVICE_CLASS_MIC) {
456 device->setMic(true);
457 }
458
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 // Switch-like devices.
460 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
461 device->addMapper(new SwitchInputMapper(device));
462 }
463
Prashant Malani1941ff52015-08-11 18:29:28 -0700464 // Scroll wheel-like devices.
465 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
466 device->addMapper(new RotaryEncoderInputMapper(device));
467 }
468
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Vibrator-like devices.
470 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
471 device->addMapper(new VibratorInputMapper(device));
472 }
473
474 // Keyboard-like devices.
475 uint32_t keyboardSource = 0;
476 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
477 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
478 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
479 }
480 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
481 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
482 }
483 if (classes & INPUT_DEVICE_CLASS_DPAD) {
484 keyboardSource |= AINPUT_SOURCE_DPAD;
485 }
486 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
487 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
488 }
489
490 if (keyboardSource != 0) {
491 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
492 }
493
494 // Cursor-like devices.
495 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
496 device->addMapper(new CursorInputMapper(device));
497 }
498
499 // Touchscreens and touchpad devices.
500 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
501 device->addMapper(new MultiTouchInputMapper(device));
502 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
503 device->addMapper(new SingleTouchInputMapper(device));
504 }
505
506 // Joystick-like devices.
507 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
508 device->addMapper(new JoystickInputMapper(device));
509 }
510
Michael Wright842500e2015-03-13 17:32:02 -0700511 // External stylus-like devices.
512 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
513 device->addMapper(new ExternalStylusInputMapper(device));
514 }
515
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 return device;
517}
518
519void InputReader::processEventsForDeviceLocked(int32_t deviceId,
520 const RawEvent* rawEvents, size_t count) {
521 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
522 if (deviceIndex < 0) {
523 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
524 return;
525 }
526
527 InputDevice* device = mDevices.valueAt(deviceIndex);
528 if (device->isIgnored()) {
529 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
530 return;
531 }
532
533 device->process(rawEvents, count);
534}
535
536void InputReader::timeoutExpiredLocked(nsecs_t when) {
537 for (size_t i = 0; i < mDevices.size(); i++) {
538 InputDevice* device = mDevices.valueAt(i);
539 if (!device->isIgnored()) {
540 device->timeoutExpired(when);
541 }
542 }
543}
544
545void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
546 // Reset global meta state because it depends on the list of all configured devices.
547 updateGlobalMetaStateLocked();
548
549 // Enqueue configuration changed.
550 NotifyConfigurationChangedArgs args(when);
551 mQueuedListener->notifyConfigurationChanged(&args);
552}
553
554void InputReader::refreshConfigurationLocked(uint32_t changes) {
555 mPolicy->getReaderConfiguration(&mConfig);
556 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
557
558 if (changes) {
559 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
560 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
561
562 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
563 mEventHub->requestReopenDevices();
564 } else {
565 for (size_t i = 0; i < mDevices.size(); i++) {
566 InputDevice* device = mDevices.valueAt(i);
567 device->configure(now, &mConfig, changes);
568 }
569 }
570 }
571}
572
573void InputReader::updateGlobalMetaStateLocked() {
574 mGlobalMetaState = 0;
575
576 for (size_t i = 0; i < mDevices.size(); i++) {
577 InputDevice* device = mDevices.valueAt(i);
578 mGlobalMetaState |= device->getMetaState();
579 }
580}
581
582int32_t InputReader::getGlobalMetaStateLocked() {
583 return mGlobalMetaState;
584}
585
Michael Wright842500e2015-03-13 17:32:02 -0700586void InputReader::notifyExternalStylusPresenceChanged() {
587 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
588}
589
590void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
591 for (size_t i = 0; i < mDevices.size(); i++) {
592 InputDevice* device = mDevices.valueAt(i);
593 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
594 outDevices.push();
595 device->getDeviceInfo(&outDevices.editTop());
596 }
597 }
598}
599
600void InputReader::dispatchExternalStylusState(const StylusState& state) {
601 for (size_t i = 0; i < mDevices.size(); i++) {
602 InputDevice* device = mDevices.valueAt(i);
603 device->updateExternalStylusState(state);
604 }
605}
606
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
608 mDisableVirtualKeysTimeout = time;
609}
610
611bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
612 InputDevice* device, int32_t keyCode, int32_t scanCode) {
613 if (now < mDisableVirtualKeysTimeout) {
614 ALOGI("Dropping virtual key from device %s because virtual keys are "
615 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100616 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 (mDisableVirtualKeysTimeout - now) * 0.000001,
618 keyCode, scanCode);
619 return true;
620 } else {
621 return false;
622 }
623}
624
625void InputReader::fadePointerLocked() {
626 for (size_t i = 0; i < mDevices.size(); i++) {
627 InputDevice* device = mDevices.valueAt(i);
628 device->fadePointer();
629 }
630}
631
632void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
633 if (when < mNextTimeout) {
634 mNextTimeout = when;
635 mEventHub->wake();
636 }
637}
638
639int32_t InputReader::bumpGenerationLocked() {
640 return ++mGeneration;
641}
642
643void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
644 AutoMutex _l(mLock);
645 getInputDevicesLocked(outInputDevices);
646}
647
648void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
649 outInputDevices.clear();
650
651 size_t numDevices = mDevices.size();
652 for (size_t i = 0; i < numDevices; i++) {
653 InputDevice* device = mDevices.valueAt(i);
654 if (!device->isIgnored()) {
655 outInputDevices.push();
656 device->getDeviceInfo(&outInputDevices.editTop());
657 }
658 }
659}
660
661int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
662 int32_t keyCode) {
663 AutoMutex _l(mLock);
664
665 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
666}
667
668int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
669 int32_t scanCode) {
670 AutoMutex _l(mLock);
671
672 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
673}
674
675int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
676 AutoMutex _l(mLock);
677
678 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
679}
680
681int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
682 GetStateFunc getStateFunc) {
683 int32_t result = AKEY_STATE_UNKNOWN;
684 if (deviceId >= 0) {
685 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
686 if (deviceIndex >= 0) {
687 InputDevice* device = mDevices.valueAt(deviceIndex);
688 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
689 result = (device->*getStateFunc)(sourceMask, code);
690 }
691 }
692 } else {
693 size_t numDevices = mDevices.size();
694 for (size_t i = 0; i < numDevices; i++) {
695 InputDevice* device = mDevices.valueAt(i);
696 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
697 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
698 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
699 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
700 if (currentResult >= AKEY_STATE_DOWN) {
701 return currentResult;
702 } else if (currentResult == AKEY_STATE_UP) {
703 result = currentResult;
704 }
705 }
706 }
707 }
708 return result;
709}
710
Andrii Kulian763a3a42016-03-08 10:46:16 -0800711void InputReader::toggleCapsLockState(int32_t deviceId) {
712 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
713 if (deviceIndex < 0) {
714 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
715 return;
716 }
717
718 InputDevice* device = mDevices.valueAt(deviceIndex);
719 if (device->isIgnored()) {
720 return;
721 }
722
723 device->updateMetaState(AKEYCODE_CAPS_LOCK);
724}
725
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
727 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
728 AutoMutex _l(mLock);
729
730 memset(outFlags, 0, numCodes);
731 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
732}
733
734bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
735 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
736 bool result = false;
737 if (deviceId >= 0) {
738 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
739 if (deviceIndex >= 0) {
740 InputDevice* device = mDevices.valueAt(deviceIndex);
741 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
742 result = device->markSupportedKeyCodes(sourceMask,
743 numCodes, keyCodes, outFlags);
744 }
745 }
746 } else {
747 size_t numDevices = mDevices.size();
748 for (size_t i = 0; i < numDevices; i++) {
749 InputDevice* device = mDevices.valueAt(i);
750 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
751 result |= device->markSupportedKeyCodes(sourceMask,
752 numCodes, keyCodes, outFlags);
753 }
754 }
755 }
756 return result;
757}
758
759void InputReader::requestRefreshConfiguration(uint32_t changes) {
760 AutoMutex _l(mLock);
761
762 if (changes) {
763 bool needWake = !mConfigurationChangesToRefresh;
764 mConfigurationChangesToRefresh |= changes;
765
766 if (needWake) {
767 mEventHub->wake();
768 }
769 }
770}
771
772void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
773 ssize_t repeat, int32_t token) {
774 AutoMutex _l(mLock);
775
776 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
777 if (deviceIndex >= 0) {
778 InputDevice* device = mDevices.valueAt(deviceIndex);
779 device->vibrate(pattern, patternSize, repeat, token);
780 }
781}
782
783void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
784 AutoMutex _l(mLock);
785
786 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
787 if (deviceIndex >= 0) {
788 InputDevice* device = mDevices.valueAt(deviceIndex);
789 device->cancelVibrate(token);
790 }
791}
792
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700793bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
794 AutoMutex _l(mLock);
795
796 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
797 if (deviceIndex >= 0) {
798 InputDevice* device = mDevices.valueAt(deviceIndex);
799 return device->isEnabled();
800 }
801 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
802 return false;
803}
804
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800805void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 AutoMutex _l(mLock);
807
808 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800809 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800811 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812
813 for (size_t i = 0; i < mDevices.size(); i++) {
814 mDevices.valueAt(i)->dump(dump);
815 }
816
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800817 dump += INDENT "Configuration:\n";
818 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
820 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800821 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100823 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800825 dump += "]\n";
826 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 mConfig.virtualKeyQuietTime * 0.000001f);
828
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800829 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
831 mConfig.pointerVelocityControlParameters.scale,
832 mConfig.pointerVelocityControlParameters.lowThreshold,
833 mConfig.pointerVelocityControlParameters.highThreshold,
834 mConfig.pointerVelocityControlParameters.acceleration);
835
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800836 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
838 mConfig.wheelVelocityControlParameters.scale,
839 mConfig.wheelVelocityControlParameters.lowThreshold,
840 mConfig.wheelVelocityControlParameters.highThreshold,
841 mConfig.wheelVelocityControlParameters.acceleration);
842
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800843 dump += StringPrintf(INDENT2 "PointerGesture:\n");
844 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800848 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800854 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800860 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800862 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800864 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800866 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700868
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800869 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700870 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871}
872
873void InputReader::monitor() {
874 // Acquire and release the lock to ensure that the reader has not deadlocked.
875 mLock.lock();
876 mEventHub->wake();
877 mReaderIsAliveCondition.wait(mLock);
878 mLock.unlock();
879
880 // Check the EventHub
881 mEventHub->monitor();
882}
883
884
885// --- InputReader::ContextImpl ---
886
887InputReader::ContextImpl::ContextImpl(InputReader* reader) :
888 mReader(reader) {
889}
890
891void InputReader::ContextImpl::updateGlobalMetaState() {
892 // lock is already held by the input loop
893 mReader->updateGlobalMetaStateLocked();
894}
895
896int32_t InputReader::ContextImpl::getGlobalMetaState() {
897 // lock is already held by the input loop
898 return mReader->getGlobalMetaStateLocked();
899}
900
901void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
902 // lock is already held by the input loop
903 mReader->disableVirtualKeysUntilLocked(time);
904}
905
906bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
907 InputDevice* device, int32_t keyCode, int32_t scanCode) {
908 // lock is already held by the input loop
909 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
910}
911
912void InputReader::ContextImpl::fadePointer() {
913 // lock is already held by the input loop
914 mReader->fadePointerLocked();
915}
916
917void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
918 // lock is already held by the input loop
919 mReader->requestTimeoutAtTimeLocked(when);
920}
921
922int32_t InputReader::ContextImpl::bumpGeneration() {
923 // lock is already held by the input loop
924 return mReader->bumpGenerationLocked();
925}
926
Michael Wright842500e2015-03-13 17:32:02 -0700927void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
928 // lock is already held by whatever called refreshConfigurationLocked
929 mReader->getExternalStylusDevicesLocked(outDevices);
930}
931
932void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
933 mReader->dispatchExternalStylusState(state);
934}
935
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
937 return mReader->mPolicy.get();
938}
939
940InputListenerInterface* InputReader::ContextImpl::getListener() {
941 return mReader->mQueuedListener.get();
942}
943
944EventHubInterface* InputReader::ContextImpl::getEventHub() {
945 return mReader->mEventHub.get();
946}
947
948
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949// --- InputDevice ---
950
951InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
952 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
953 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
954 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700955 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
958InputDevice::~InputDevice() {
959 size_t numMappers = mMappers.size();
960 for (size_t i = 0; i < numMappers; i++) {
961 delete mMappers[i];
962 }
963 mMappers.clear();
964}
965
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700966bool InputDevice::isEnabled() {
967 return getEventHub()->isDeviceEnabled(mId);
968}
969
970void InputDevice::setEnabled(bool enabled, nsecs_t when) {
971 if (isEnabled() == enabled) {
972 return;
973 }
974
975 if (enabled) {
976 getEventHub()->enableDevice(mId);
977 reset(when);
978 } else {
979 reset(when);
980 getEventHub()->disableDevice(mId);
981 }
982 // Must change generation to flag this device as changed
983 bumpGeneration();
984}
985
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800986void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700988 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800990 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100991 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
993 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -0700994 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
995 if (mAssociatedDisplayPort) {
996 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
997 } else {
998 dump += "<none>\n";
999 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001000 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1001 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1002 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003
1004 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1005 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001006 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 for (size_t i = 0; i < ranges.size(); i++) {
1008 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1009 const char* label = getAxisLabel(range.axis);
1010 char name[32];
1011 if (label) {
1012 strncpy(name, label, sizeof(name));
1013 name[sizeof(name) - 1] = '\0';
1014 } else {
1015 snprintf(name, sizeof(name), "%d", range.axis);
1016 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001017 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1019 name, range.source, range.min, range.max, range.flat, range.fuzz,
1020 range.resolution);
1021 }
1022 }
1023
1024 size_t numMappers = mMappers.size();
1025 for (size_t i = 0; i < numMappers; i++) {
1026 InputMapper* mapper = mMappers[i];
1027 mapper->dump(dump);
1028 }
1029}
1030
1031void InputDevice::addMapper(InputMapper* mapper) {
1032 mMappers.add(mapper);
1033}
1034
1035void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1036 mSources = 0;
1037
1038 if (!isIgnored()) {
1039 if (!changes) { // first time only
1040 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1041 }
1042
1043 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1044 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1045 sp<KeyCharacterMap> keyboardLayout =
1046 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1047 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1048 bumpGeneration();
1049 }
1050 }
1051 }
1052
1053 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1054 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001055 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 if (mAlias != alias) {
1057 mAlias = alias;
1058 bumpGeneration();
1059 }
1060 }
1061 }
1062
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001063 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1064 ssize_t index = config->disabledDevices.indexOf(mId);
1065 bool enabled = index < 0;
1066 setEnabled(enabled, when);
1067 }
1068
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001069 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1070 // In most situations, no port will be specified.
1071 mAssociatedDisplayPort = std::nullopt;
1072 // Find the display port that corresponds to the current input port.
1073 const std::string& inputPort = mIdentifier.location;
1074 if (!inputPort.empty()) {
1075 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1076 const auto& displayPort = ports.find(inputPort);
1077 if (displayPort != ports.end()) {
1078 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1079 }
1080 }
1081 }
1082
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 size_t numMappers = mMappers.size();
1084 for (size_t i = 0; i < numMappers; i++) {
1085 InputMapper* mapper = mMappers[i];
1086 mapper->configure(when, config, changes);
1087 mSources |= mapper->getSources();
1088 }
1089 }
1090}
1091
1092void InputDevice::reset(nsecs_t when) {
1093 size_t numMappers = mMappers.size();
1094 for (size_t i = 0; i < numMappers; i++) {
1095 InputMapper* mapper = mMappers[i];
1096 mapper->reset(when);
1097 }
1098
1099 mContext->updateGlobalMetaState();
1100
1101 notifyReset(when);
1102}
1103
1104void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1105 // Process all of the events in order for each mapper.
1106 // We cannot simply ask each mapper to process them in bulk because mappers may
1107 // have side-effects that must be interleaved. For example, joystick movement events and
1108 // gamepad button presses are handled by different mappers but they should be dispatched
1109 // in the order received.
1110 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001111 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001113 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1115 rawEvent->when);
1116#endif
1117
1118 if (mDropUntilNextSync) {
1119 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1120 mDropUntilNextSync = false;
1121#if DEBUG_RAW_EVENTS
1122 ALOGD("Recovered from input event buffer overrun.");
1123#endif
1124 } else {
1125#if DEBUG_RAW_EVENTS
1126 ALOGD("Dropped input event while waiting for next input sync.");
1127#endif
1128 }
1129 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001130 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 mDropUntilNextSync = true;
1132 reset(rawEvent->when);
1133 } else {
1134 for (size_t i = 0; i < numMappers; i++) {
1135 InputMapper* mapper = mMappers[i];
1136 mapper->process(rawEvent);
1137 }
1138 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001139 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141}
1142
1143void InputDevice::timeoutExpired(nsecs_t when) {
1144 size_t numMappers = mMappers.size();
1145 for (size_t i = 0; i < numMappers; i++) {
1146 InputMapper* mapper = mMappers[i];
1147 mapper->timeoutExpired(when);
1148 }
1149}
1150
Michael Wright842500e2015-03-13 17:32:02 -07001151void InputDevice::updateExternalStylusState(const StylusState& state) {
1152 size_t numMappers = mMappers.size();
1153 for (size_t i = 0; i < numMappers; i++) {
1154 InputMapper* mapper = mMappers[i];
1155 mapper->updateExternalStylusState(state);
1156 }
1157}
1158
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1160 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001161 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 size_t numMappers = mMappers.size();
1163 for (size_t i = 0; i < numMappers; i++) {
1164 InputMapper* mapper = mMappers[i];
1165 mapper->populateDeviceInfo(outDeviceInfo);
1166 }
1167}
1168
1169int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1170 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1171}
1172
1173int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1174 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1175}
1176
1177int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1178 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1179}
1180
1181int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1182 int32_t result = AKEY_STATE_UNKNOWN;
1183 size_t numMappers = mMappers.size();
1184 for (size_t i = 0; i < numMappers; i++) {
1185 InputMapper* mapper = mMappers[i];
1186 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1187 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1188 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1189 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1190 if (currentResult >= AKEY_STATE_DOWN) {
1191 return currentResult;
1192 } else if (currentResult == AKEY_STATE_UP) {
1193 result = currentResult;
1194 }
1195 }
1196 }
1197 return result;
1198}
1199
1200bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1201 const int32_t* keyCodes, uint8_t* outFlags) {
1202 bool result = false;
1203 size_t numMappers = mMappers.size();
1204 for (size_t i = 0; i < numMappers; i++) {
1205 InputMapper* mapper = mMappers[i];
1206 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1207 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1208 }
1209 }
1210 return result;
1211}
1212
1213void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1214 int32_t token) {
1215 size_t numMappers = mMappers.size();
1216 for (size_t i = 0; i < numMappers; i++) {
1217 InputMapper* mapper = mMappers[i];
1218 mapper->vibrate(pattern, patternSize, repeat, token);
1219 }
1220}
1221
1222void InputDevice::cancelVibrate(int32_t token) {
1223 size_t numMappers = mMappers.size();
1224 for (size_t i = 0; i < numMappers; i++) {
1225 InputMapper* mapper = mMappers[i];
1226 mapper->cancelVibrate(token);
1227 }
1228}
1229
Jeff Brownc9aa6282015-02-11 19:03:28 -08001230void InputDevice::cancelTouch(nsecs_t when) {
1231 size_t numMappers = mMappers.size();
1232 for (size_t i = 0; i < numMappers; i++) {
1233 InputMapper* mapper = mMappers[i];
1234 mapper->cancelTouch(when);
1235 }
1236}
1237
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238int32_t InputDevice::getMetaState() {
1239 int32_t result = 0;
1240 size_t numMappers = mMappers.size();
1241 for (size_t i = 0; i < numMappers; i++) {
1242 InputMapper* mapper = mMappers[i];
1243 result |= mapper->getMetaState();
1244 }
1245 return result;
1246}
1247
Andrii Kulian763a3a42016-03-08 10:46:16 -08001248void InputDevice::updateMetaState(int32_t keyCode) {
1249 size_t numMappers = mMappers.size();
1250 for (size_t i = 0; i < numMappers; i++) {
1251 mMappers[i]->updateMetaState(keyCode);
1252 }
1253}
1254
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255void InputDevice::fadePointer() {
1256 size_t numMappers = mMappers.size();
1257 for (size_t i = 0; i < numMappers; i++) {
1258 InputMapper* mapper = mMappers[i];
1259 mapper->fadePointer();
1260 }
1261}
1262
1263void InputDevice::bumpGeneration() {
1264 mGeneration = mContext->bumpGeneration();
1265}
1266
1267void InputDevice::notifyReset(nsecs_t when) {
1268 NotifyDeviceResetArgs args(when, mId);
1269 mContext->getListener()->notifyDeviceReset(&args);
1270}
1271
1272
1273// --- CursorButtonAccumulator ---
1274
1275CursorButtonAccumulator::CursorButtonAccumulator() {
1276 clearButtons();
1277}
1278
1279void CursorButtonAccumulator::reset(InputDevice* device) {
1280 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1281 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1282 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1283 mBtnBack = device->isKeyPressed(BTN_BACK);
1284 mBtnSide = device->isKeyPressed(BTN_SIDE);
1285 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1286 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1287 mBtnTask = device->isKeyPressed(BTN_TASK);
1288}
1289
1290void CursorButtonAccumulator::clearButtons() {
1291 mBtnLeft = 0;
1292 mBtnRight = 0;
1293 mBtnMiddle = 0;
1294 mBtnBack = 0;
1295 mBtnSide = 0;
1296 mBtnForward = 0;
1297 mBtnExtra = 0;
1298 mBtnTask = 0;
1299}
1300
1301void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1302 if (rawEvent->type == EV_KEY) {
1303 switch (rawEvent->code) {
1304 case BTN_LEFT:
1305 mBtnLeft = rawEvent->value;
1306 break;
1307 case BTN_RIGHT:
1308 mBtnRight = rawEvent->value;
1309 break;
1310 case BTN_MIDDLE:
1311 mBtnMiddle = rawEvent->value;
1312 break;
1313 case BTN_BACK:
1314 mBtnBack = rawEvent->value;
1315 break;
1316 case BTN_SIDE:
1317 mBtnSide = rawEvent->value;
1318 break;
1319 case BTN_FORWARD:
1320 mBtnForward = rawEvent->value;
1321 break;
1322 case BTN_EXTRA:
1323 mBtnExtra = rawEvent->value;
1324 break;
1325 case BTN_TASK:
1326 mBtnTask = rawEvent->value;
1327 break;
1328 }
1329 }
1330}
1331
1332uint32_t CursorButtonAccumulator::getButtonState() const {
1333 uint32_t result = 0;
1334 if (mBtnLeft) {
1335 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1336 }
1337 if (mBtnRight) {
1338 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1339 }
1340 if (mBtnMiddle) {
1341 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1342 }
1343 if (mBtnBack || mBtnSide) {
1344 result |= AMOTION_EVENT_BUTTON_BACK;
1345 }
1346 if (mBtnForward || mBtnExtra) {
1347 result |= AMOTION_EVENT_BUTTON_FORWARD;
1348 }
1349 return result;
1350}
1351
1352
1353// --- CursorMotionAccumulator ---
1354
1355CursorMotionAccumulator::CursorMotionAccumulator() {
1356 clearRelativeAxes();
1357}
1358
1359void CursorMotionAccumulator::reset(InputDevice* device) {
1360 clearRelativeAxes();
1361}
1362
1363void CursorMotionAccumulator::clearRelativeAxes() {
1364 mRelX = 0;
1365 mRelY = 0;
1366}
1367
1368void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1369 if (rawEvent->type == EV_REL) {
1370 switch (rawEvent->code) {
1371 case REL_X:
1372 mRelX = rawEvent->value;
1373 break;
1374 case REL_Y:
1375 mRelY = rawEvent->value;
1376 break;
1377 }
1378 }
1379}
1380
1381void CursorMotionAccumulator::finishSync() {
1382 clearRelativeAxes();
1383}
1384
1385
1386// --- CursorScrollAccumulator ---
1387
1388CursorScrollAccumulator::CursorScrollAccumulator() :
1389 mHaveRelWheel(false), mHaveRelHWheel(false) {
1390 clearRelativeAxes();
1391}
1392
1393void CursorScrollAccumulator::configure(InputDevice* device) {
1394 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1395 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1396}
1397
1398void CursorScrollAccumulator::reset(InputDevice* device) {
1399 clearRelativeAxes();
1400}
1401
1402void CursorScrollAccumulator::clearRelativeAxes() {
1403 mRelWheel = 0;
1404 mRelHWheel = 0;
1405}
1406
1407void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1408 if (rawEvent->type == EV_REL) {
1409 switch (rawEvent->code) {
1410 case REL_WHEEL:
1411 mRelWheel = rawEvent->value;
1412 break;
1413 case REL_HWHEEL:
1414 mRelHWheel = rawEvent->value;
1415 break;
1416 }
1417 }
1418}
1419
1420void CursorScrollAccumulator::finishSync() {
1421 clearRelativeAxes();
1422}
1423
1424
1425// --- TouchButtonAccumulator ---
1426
1427TouchButtonAccumulator::TouchButtonAccumulator() :
1428 mHaveBtnTouch(false), mHaveStylus(false) {
1429 clearButtons();
1430}
1431
1432void TouchButtonAccumulator::configure(InputDevice* device) {
1433 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1434 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1435 || device->hasKey(BTN_TOOL_RUBBER)
1436 || device->hasKey(BTN_TOOL_BRUSH)
1437 || device->hasKey(BTN_TOOL_PENCIL)
1438 || device->hasKey(BTN_TOOL_AIRBRUSH);
1439}
1440
1441void TouchButtonAccumulator::reset(InputDevice* device) {
1442 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1443 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001444 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1445 mBtnStylus2 =
1446 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1448 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1449 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1450 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1451 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1452 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1453 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1454 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1455 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1456 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1457 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1458}
1459
1460void TouchButtonAccumulator::clearButtons() {
1461 mBtnTouch = 0;
1462 mBtnStylus = 0;
1463 mBtnStylus2 = 0;
1464 mBtnToolFinger = 0;
1465 mBtnToolPen = 0;
1466 mBtnToolRubber = 0;
1467 mBtnToolBrush = 0;
1468 mBtnToolPencil = 0;
1469 mBtnToolAirbrush = 0;
1470 mBtnToolMouse = 0;
1471 mBtnToolLens = 0;
1472 mBtnToolDoubleTap = 0;
1473 mBtnToolTripleTap = 0;
1474 mBtnToolQuadTap = 0;
1475}
1476
1477void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1478 if (rawEvent->type == EV_KEY) {
1479 switch (rawEvent->code) {
1480 case BTN_TOUCH:
1481 mBtnTouch = rawEvent->value;
1482 break;
1483 case BTN_STYLUS:
1484 mBtnStylus = rawEvent->value;
1485 break;
1486 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001487 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 mBtnStylus2 = rawEvent->value;
1489 break;
1490 case BTN_TOOL_FINGER:
1491 mBtnToolFinger = rawEvent->value;
1492 break;
1493 case BTN_TOOL_PEN:
1494 mBtnToolPen = rawEvent->value;
1495 break;
1496 case BTN_TOOL_RUBBER:
1497 mBtnToolRubber = rawEvent->value;
1498 break;
1499 case BTN_TOOL_BRUSH:
1500 mBtnToolBrush = rawEvent->value;
1501 break;
1502 case BTN_TOOL_PENCIL:
1503 mBtnToolPencil = rawEvent->value;
1504 break;
1505 case BTN_TOOL_AIRBRUSH:
1506 mBtnToolAirbrush = rawEvent->value;
1507 break;
1508 case BTN_TOOL_MOUSE:
1509 mBtnToolMouse = rawEvent->value;
1510 break;
1511 case BTN_TOOL_LENS:
1512 mBtnToolLens = rawEvent->value;
1513 break;
1514 case BTN_TOOL_DOUBLETAP:
1515 mBtnToolDoubleTap = rawEvent->value;
1516 break;
1517 case BTN_TOOL_TRIPLETAP:
1518 mBtnToolTripleTap = rawEvent->value;
1519 break;
1520 case BTN_TOOL_QUADTAP:
1521 mBtnToolQuadTap = rawEvent->value;
1522 break;
1523 }
1524 }
1525}
1526
1527uint32_t TouchButtonAccumulator::getButtonState() const {
1528 uint32_t result = 0;
1529 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001530 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001533 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 }
1535 return result;
1536}
1537
1538int32_t TouchButtonAccumulator::getToolType() const {
1539 if (mBtnToolMouse || mBtnToolLens) {
1540 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1541 }
1542 if (mBtnToolRubber) {
1543 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1544 }
1545 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1546 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1547 }
1548 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1549 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1550 }
1551 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1552}
1553
1554bool TouchButtonAccumulator::isToolActive() const {
1555 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1556 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1557 || mBtnToolMouse || mBtnToolLens
1558 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1559}
1560
1561bool TouchButtonAccumulator::isHovering() const {
1562 return mHaveBtnTouch && !mBtnTouch;
1563}
1564
1565bool TouchButtonAccumulator::hasStylus() const {
1566 return mHaveStylus;
1567}
1568
1569
1570// --- RawPointerAxes ---
1571
1572RawPointerAxes::RawPointerAxes() {
1573 clear();
1574}
1575
1576void RawPointerAxes::clear() {
1577 x.clear();
1578 y.clear();
1579 pressure.clear();
1580 touchMajor.clear();
1581 touchMinor.clear();
1582 toolMajor.clear();
1583 toolMinor.clear();
1584 orientation.clear();
1585 distance.clear();
1586 tiltX.clear();
1587 tiltY.clear();
1588 trackingId.clear();
1589 slot.clear();
1590}
1591
1592
1593// --- RawPointerData ---
1594
1595RawPointerData::RawPointerData() {
1596 clear();
1597}
1598
1599void RawPointerData::clear() {
1600 pointerCount = 0;
1601 clearIdBits();
1602}
1603
1604void RawPointerData::copyFrom(const RawPointerData& other) {
1605 pointerCount = other.pointerCount;
1606 hoveringIdBits = other.hoveringIdBits;
1607 touchingIdBits = other.touchingIdBits;
1608
1609 for (uint32_t i = 0; i < pointerCount; i++) {
1610 pointers[i] = other.pointers[i];
1611
1612 int id = pointers[i].id;
1613 idToIndex[id] = other.idToIndex[id];
1614 }
1615}
1616
1617void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1618 float x = 0, y = 0;
1619 uint32_t count = touchingIdBits.count();
1620 if (count) {
1621 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1622 uint32_t id = idBits.clearFirstMarkedBit();
1623 const Pointer& pointer = pointerForId(id);
1624 x += pointer.x;
1625 y += pointer.y;
1626 }
1627 x /= count;
1628 y /= count;
1629 }
1630 *outX = x;
1631 *outY = y;
1632}
1633
1634
1635// --- CookedPointerData ---
1636
1637CookedPointerData::CookedPointerData() {
1638 clear();
1639}
1640
1641void CookedPointerData::clear() {
1642 pointerCount = 0;
1643 hoveringIdBits.clear();
1644 touchingIdBits.clear();
1645}
1646
1647void CookedPointerData::copyFrom(const CookedPointerData& other) {
1648 pointerCount = other.pointerCount;
1649 hoveringIdBits = other.hoveringIdBits;
1650 touchingIdBits = other.touchingIdBits;
1651
1652 for (uint32_t i = 0; i < pointerCount; i++) {
1653 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1654 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1655
1656 int id = pointerProperties[i].id;
1657 idToIndex[id] = other.idToIndex[id];
1658 }
1659}
1660
1661
1662// --- SingleTouchMotionAccumulator ---
1663
1664SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1665 clearAbsoluteAxes();
1666}
1667
1668void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1669 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1670 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1671 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1672 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1673 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1674 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1675 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1676}
1677
1678void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1679 mAbsX = 0;
1680 mAbsY = 0;
1681 mAbsPressure = 0;
1682 mAbsToolWidth = 0;
1683 mAbsDistance = 0;
1684 mAbsTiltX = 0;
1685 mAbsTiltY = 0;
1686}
1687
1688void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1689 if (rawEvent->type == EV_ABS) {
1690 switch (rawEvent->code) {
1691 case ABS_X:
1692 mAbsX = rawEvent->value;
1693 break;
1694 case ABS_Y:
1695 mAbsY = rawEvent->value;
1696 break;
1697 case ABS_PRESSURE:
1698 mAbsPressure = rawEvent->value;
1699 break;
1700 case ABS_TOOL_WIDTH:
1701 mAbsToolWidth = rawEvent->value;
1702 break;
1703 case ABS_DISTANCE:
1704 mAbsDistance = rawEvent->value;
1705 break;
1706 case ABS_TILT_X:
1707 mAbsTiltX = rawEvent->value;
1708 break;
1709 case ABS_TILT_Y:
1710 mAbsTiltY = rawEvent->value;
1711 break;
1712 }
1713 }
1714}
1715
1716
1717// --- MultiTouchMotionAccumulator ---
1718
1719MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001721 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722}
1723
1724MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1725 delete[] mSlots;
1726}
1727
1728void MultiTouchMotionAccumulator::configure(InputDevice* device,
1729 size_t slotCount, bool usingSlotsProtocol) {
1730 mSlotCount = slotCount;
1731 mUsingSlotsProtocol = usingSlotsProtocol;
1732 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1733
1734 delete[] mSlots;
1735 mSlots = new Slot[slotCount];
1736}
1737
1738void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1739 // Unfortunately there is no way to read the initial contents of the slots.
1740 // So when we reset the accumulator, we must assume they are all zeroes.
1741 if (mUsingSlotsProtocol) {
1742 // Query the driver for the current slot index and use it as the initial slot
1743 // before we start reading events from the device. It is possible that the
1744 // current slot index will not be the same as it was when the first event was
1745 // written into the evdev buffer, which means the input mapper could start
1746 // out of sync with the initial state of the events in the evdev buffer.
1747 // In the extremely unlikely case that this happens, the data from
1748 // two slots will be confused until the next ABS_MT_SLOT event is received.
1749 // This can cause the touch point to "jump", but at least there will be
1750 // no stuck touches.
1751 int32_t initialSlot;
1752 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1753 ABS_MT_SLOT, &initialSlot);
1754 if (status) {
1755 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1756 initialSlot = -1;
1757 }
1758 clearSlots(initialSlot);
1759 } else {
1760 clearSlots(-1);
1761 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001762 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763}
1764
1765void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1766 if (mSlots) {
1767 for (size_t i = 0; i < mSlotCount; i++) {
1768 mSlots[i].clear();
1769 }
1770 }
1771 mCurrentSlot = initialSlot;
1772}
1773
1774void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1775 if (rawEvent->type == EV_ABS) {
1776 bool newSlot = false;
1777 if (mUsingSlotsProtocol) {
1778 if (rawEvent->code == ABS_MT_SLOT) {
1779 mCurrentSlot = rawEvent->value;
1780 newSlot = true;
1781 }
1782 } else if (mCurrentSlot < 0) {
1783 mCurrentSlot = 0;
1784 }
1785
1786 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1787#if DEBUG_POINTERS
1788 if (newSlot) {
1789 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001790 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 mCurrentSlot, mSlotCount - 1);
1792 }
1793#endif
1794 } else {
1795 Slot* slot = &mSlots[mCurrentSlot];
1796
1797 switch (rawEvent->code) {
1798 case ABS_MT_POSITION_X:
1799 slot->mInUse = true;
1800 slot->mAbsMTPositionX = rawEvent->value;
1801 break;
1802 case ABS_MT_POSITION_Y:
1803 slot->mInUse = true;
1804 slot->mAbsMTPositionY = rawEvent->value;
1805 break;
1806 case ABS_MT_TOUCH_MAJOR:
1807 slot->mInUse = true;
1808 slot->mAbsMTTouchMajor = rawEvent->value;
1809 break;
1810 case ABS_MT_TOUCH_MINOR:
1811 slot->mInUse = true;
1812 slot->mAbsMTTouchMinor = rawEvent->value;
1813 slot->mHaveAbsMTTouchMinor = true;
1814 break;
1815 case ABS_MT_WIDTH_MAJOR:
1816 slot->mInUse = true;
1817 slot->mAbsMTWidthMajor = rawEvent->value;
1818 break;
1819 case ABS_MT_WIDTH_MINOR:
1820 slot->mInUse = true;
1821 slot->mAbsMTWidthMinor = rawEvent->value;
1822 slot->mHaveAbsMTWidthMinor = true;
1823 break;
1824 case ABS_MT_ORIENTATION:
1825 slot->mInUse = true;
1826 slot->mAbsMTOrientation = rawEvent->value;
1827 break;
1828 case ABS_MT_TRACKING_ID:
1829 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1830 // The slot is no longer in use but it retains its previous contents,
1831 // which may be reused for subsequent touches.
1832 slot->mInUse = false;
1833 } else {
1834 slot->mInUse = true;
1835 slot->mAbsMTTrackingId = rawEvent->value;
1836 }
1837 break;
1838 case ABS_MT_PRESSURE:
1839 slot->mInUse = true;
1840 slot->mAbsMTPressure = rawEvent->value;
1841 break;
1842 case ABS_MT_DISTANCE:
1843 slot->mInUse = true;
1844 slot->mAbsMTDistance = rawEvent->value;
1845 break;
1846 case ABS_MT_TOOL_TYPE:
1847 slot->mInUse = true;
1848 slot->mAbsMTToolType = rawEvent->value;
1849 slot->mHaveAbsMTToolType = true;
1850 break;
1851 }
1852 }
1853 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1854 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1855 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001856 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1857 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
1859}
1860
1861void MultiTouchMotionAccumulator::finishSync() {
1862 if (!mUsingSlotsProtocol) {
1863 clearSlots(-1);
1864 }
1865}
1866
1867bool MultiTouchMotionAccumulator::hasStylus() const {
1868 return mHaveStylus;
1869}
1870
1871
1872// --- MultiTouchMotionAccumulator::Slot ---
1873
1874MultiTouchMotionAccumulator::Slot::Slot() {
1875 clear();
1876}
1877
1878void MultiTouchMotionAccumulator::Slot::clear() {
1879 mInUse = false;
1880 mHaveAbsMTTouchMinor = false;
1881 mHaveAbsMTWidthMinor = false;
1882 mHaveAbsMTToolType = false;
1883 mAbsMTPositionX = 0;
1884 mAbsMTPositionY = 0;
1885 mAbsMTTouchMajor = 0;
1886 mAbsMTTouchMinor = 0;
1887 mAbsMTWidthMajor = 0;
1888 mAbsMTWidthMinor = 0;
1889 mAbsMTOrientation = 0;
1890 mAbsMTTrackingId = -1;
1891 mAbsMTPressure = 0;
1892 mAbsMTDistance = 0;
1893 mAbsMTToolType = 0;
1894}
1895
1896int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1897 if (mHaveAbsMTToolType) {
1898 switch (mAbsMTToolType) {
1899 case MT_TOOL_FINGER:
1900 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1901 case MT_TOOL_PEN:
1902 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1903 }
1904 }
1905 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1906}
1907
1908
1909// --- InputMapper ---
1910
1911InputMapper::InputMapper(InputDevice* device) :
1912 mDevice(device), mContext(device->getContext()) {
1913}
1914
1915InputMapper::~InputMapper() {
1916}
1917
1918void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1919 info->addSource(getSources());
1920}
1921
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001922void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923}
1924
1925void InputMapper::configure(nsecs_t when,
1926 const InputReaderConfiguration* config, uint32_t changes) {
1927}
1928
1929void InputMapper::reset(nsecs_t when) {
1930}
1931
1932void InputMapper::timeoutExpired(nsecs_t when) {
1933}
1934
1935int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1936 return AKEY_STATE_UNKNOWN;
1937}
1938
1939int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1940 return AKEY_STATE_UNKNOWN;
1941}
1942
1943int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1944 return AKEY_STATE_UNKNOWN;
1945}
1946
1947bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1948 const int32_t* keyCodes, uint8_t* outFlags) {
1949 return false;
1950}
1951
1952void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1953 int32_t token) {
1954}
1955
1956void InputMapper::cancelVibrate(int32_t token) {
1957}
1958
Jeff Brownc9aa6282015-02-11 19:03:28 -08001959void InputMapper::cancelTouch(nsecs_t when) {
1960}
1961
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962int32_t InputMapper::getMetaState() {
1963 return 0;
1964}
1965
Andrii Kulian763a3a42016-03-08 10:46:16 -08001966void InputMapper::updateMetaState(int32_t keyCode) {
1967}
1968
Michael Wright842500e2015-03-13 17:32:02 -07001969void InputMapper::updateExternalStylusState(const StylusState& state) {
1970
1971}
1972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973void InputMapper::fadePointer() {
1974}
1975
1976status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1977 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1978}
1979
1980void InputMapper::bumpGeneration() {
1981 mDevice->bumpGeneration();
1982}
1983
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001984void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 const RawAbsoluteAxisInfo& axis, const char* name) {
1986 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001987 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1989 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001990 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992}
1993
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001994void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1995 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1996 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
1997 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
1998 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07001999}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
2001// --- SwitchInputMapper ---
2002
2003SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002004 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005}
2006
2007SwitchInputMapper::~SwitchInputMapper() {
2008}
2009
2010uint32_t SwitchInputMapper::getSources() {
2011 return AINPUT_SOURCE_SWITCH;
2012}
2013
2014void SwitchInputMapper::process(const RawEvent* rawEvent) {
2015 switch (rawEvent->type) {
2016 case EV_SW:
2017 processSwitch(rawEvent->code, rawEvent->value);
2018 break;
2019
2020 case EV_SYN:
2021 if (rawEvent->code == SYN_REPORT) {
2022 sync(rawEvent->when);
2023 }
2024 }
2025}
2026
2027void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2028 if (switchCode >= 0 && switchCode < 32) {
2029 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002030 mSwitchValues |= 1 << switchCode;
2031 } else {
2032 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034 mUpdatedSwitchMask |= 1 << switchCode;
2035 }
2036}
2037
2038void SwitchInputMapper::sync(nsecs_t when) {
2039 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002040 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002041 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 getListener()->notifySwitch(&args);
2043
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 mUpdatedSwitchMask = 0;
2045 }
2046}
2047
2048int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2049 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2050}
2051
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002052void SwitchInputMapper::dump(std::string& dump) {
2053 dump += INDENT2 "Switch Input Mapper:\n";
2054 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002055}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056
2057// --- VibratorInputMapper ---
2058
2059VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2060 InputMapper(device), mVibrating(false) {
2061}
2062
2063VibratorInputMapper::~VibratorInputMapper() {
2064}
2065
2066uint32_t VibratorInputMapper::getSources() {
2067 return 0;
2068}
2069
2070void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2071 InputMapper::populateDeviceInfo(info);
2072
2073 info->setVibrator(true);
2074}
2075
2076void VibratorInputMapper::process(const RawEvent* rawEvent) {
2077 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2078}
2079
2080void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2081 int32_t token) {
2082#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002083 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 for (size_t i = 0; i < patternSize; i++) {
2085 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002086 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002088 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002090 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002091 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092#endif
2093
2094 mVibrating = true;
2095 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2096 mPatternSize = patternSize;
2097 mRepeat = repeat;
2098 mToken = token;
2099 mIndex = -1;
2100
2101 nextStep();
2102}
2103
2104void VibratorInputMapper::cancelVibrate(int32_t token) {
2105#if DEBUG_VIBRATOR
2106 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2107#endif
2108
2109 if (mVibrating && mToken == token) {
2110 stopVibrating();
2111 }
2112}
2113
2114void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2115 if (mVibrating) {
2116 if (when >= mNextStepTime) {
2117 nextStep();
2118 } else {
2119 getContext()->requestTimeoutAtTime(mNextStepTime);
2120 }
2121 }
2122}
2123
2124void VibratorInputMapper::nextStep() {
2125 mIndex += 1;
2126 if (size_t(mIndex) >= mPatternSize) {
2127 if (mRepeat < 0) {
2128 // We are done.
2129 stopVibrating();
2130 return;
2131 }
2132 mIndex = mRepeat;
2133 }
2134
2135 bool vibratorOn = mIndex & 1;
2136 nsecs_t duration = mPattern[mIndex];
2137 if (vibratorOn) {
2138#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002139 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140#endif
2141 getEventHub()->vibrate(getDeviceId(), duration);
2142 } else {
2143#if DEBUG_VIBRATOR
2144 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2145#endif
2146 getEventHub()->cancelVibrate(getDeviceId());
2147 }
2148 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2149 mNextStepTime = now + duration;
2150 getContext()->requestTimeoutAtTime(mNextStepTime);
2151#if DEBUG_VIBRATOR
2152 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2153#endif
2154}
2155
2156void VibratorInputMapper::stopVibrating() {
2157 mVibrating = false;
2158#if DEBUG_VIBRATOR
2159 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2160#endif
2161 getEventHub()->cancelVibrate(getDeviceId());
2162}
2163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002164void VibratorInputMapper::dump(std::string& dump) {
2165 dump += INDENT2 "Vibrator Input Mapper:\n";
2166 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167}
2168
2169
2170// --- KeyboardInputMapper ---
2171
2172KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2173 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002174 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175}
2176
2177KeyboardInputMapper::~KeyboardInputMapper() {
2178}
2179
2180uint32_t KeyboardInputMapper::getSources() {
2181 return mSource;
2182}
2183
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002184int32_t KeyboardInputMapper::getOrientation() {
2185 if (mViewport) {
2186 return mViewport->orientation;
2187 }
2188 return DISPLAY_ORIENTATION_0;
2189}
2190
2191int32_t KeyboardInputMapper::getDisplayId() {
2192 if (mViewport) {
2193 return mViewport->displayId;
2194 }
2195 return ADISPLAY_ID_NONE;
2196}
2197
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2199 InputMapper::populateDeviceInfo(info);
2200
2201 info->setKeyboardType(mKeyboardType);
2202 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2203}
2204
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002205void KeyboardInputMapper::dump(std::string& dump) {
2206 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002208 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002209 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002210 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2211 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2212 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213}
2214
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215void KeyboardInputMapper::configure(nsecs_t when,
2216 const InputReaderConfiguration* config, uint32_t changes) {
2217 InputMapper::configure(when, config, changes);
2218
2219 if (!changes) { // first time only
2220 // Configure basic parameters.
2221 configureParameters();
2222 }
2223
2224 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002225 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002226 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228 }
2229}
2230
Ivan Podogovb9afef32017-02-13 15:34:32 +00002231static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2232 int32_t mapped = 0;
2233 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2234 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2235 if (stemKeyRotationMap[i][0] == keyCode) {
2236 stemKeyRotationMap[i][1] = mapped;
2237 return;
2238 }
2239 }
2240 }
2241}
2242
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243void KeyboardInputMapper::configureParameters() {
2244 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002245 const PropertyMap& config = getDevice()->getConfiguration();
2246 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 mParameters.orientationAware);
2248
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002250 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2251 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2252 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2253 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002255
2256 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002257 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002258 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259}
2260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002261void KeyboardInputMapper::dumpParameters(std::string& dump) {
2262 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002263 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002265 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002266 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267}
2268
2269void KeyboardInputMapper::reset(nsecs_t when) {
2270 mMetaState = AMETA_NONE;
2271 mDownTime = 0;
2272 mKeyDowns.clear();
2273 mCurrentHidUsage = 0;
2274
2275 resetLedState();
2276
2277 InputMapper::reset(when);
2278}
2279
2280void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2281 switch (rawEvent->type) {
2282 case EV_KEY: {
2283 int32_t scanCode = rawEvent->code;
2284 int32_t usageCode = mCurrentHidUsage;
2285 mCurrentHidUsage = 0;
2286
2287 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002288 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290 break;
2291 }
2292 case EV_MSC: {
2293 if (rawEvent->code == MSC_SCAN) {
2294 mCurrentHidUsage = rawEvent->value;
2295 }
2296 break;
2297 }
2298 case EV_SYN: {
2299 if (rawEvent->code == SYN_REPORT) {
2300 mCurrentHidUsage = 0;
2301 }
2302 }
2303 }
2304}
2305
2306bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2307 return scanCode < BTN_MOUSE
2308 || scanCode >= KEY_OK
2309 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2310 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2311}
2312
Michael Wright58ba9882017-07-26 16:19:11 +01002313bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2314 switch (keyCode) {
2315 case AKEYCODE_MEDIA_PLAY:
2316 case AKEYCODE_MEDIA_PAUSE:
2317 case AKEYCODE_MEDIA_PLAY_PAUSE:
2318 case AKEYCODE_MUTE:
2319 case AKEYCODE_HEADSETHOOK:
2320 case AKEYCODE_MEDIA_STOP:
2321 case AKEYCODE_MEDIA_NEXT:
2322 case AKEYCODE_MEDIA_PREVIOUS:
2323 case AKEYCODE_MEDIA_REWIND:
2324 case AKEYCODE_MEDIA_RECORD:
2325 case AKEYCODE_MEDIA_FAST_FORWARD:
2326 case AKEYCODE_MEDIA_SKIP_FORWARD:
2327 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2328 case AKEYCODE_MEDIA_STEP_FORWARD:
2329 case AKEYCODE_MEDIA_STEP_BACKWARD:
2330 case AKEYCODE_MEDIA_AUDIO_TRACK:
2331 case AKEYCODE_VOLUME_UP:
2332 case AKEYCODE_VOLUME_DOWN:
2333 case AKEYCODE_VOLUME_MUTE:
2334 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2335 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2336 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2337 return true;
2338 }
2339 return false;
2340}
2341
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002342void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2343 int32_t usageCode) {
2344 int32_t keyCode;
2345 int32_t keyMetaState;
2346 uint32_t policyFlags;
2347
2348 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2349 &keyCode, &keyMetaState, &policyFlags)) {
2350 keyCode = AKEYCODE_UNKNOWN;
2351 keyMetaState = mMetaState;
2352 policyFlags = 0;
2353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
2355 if (down) {
2356 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002357 if (mParameters.orientationAware) {
2358 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
2360
2361 // Add key down.
2362 ssize_t keyDownIndex = findKeyDown(scanCode);
2363 if (keyDownIndex >= 0) {
2364 // key repeat, be sure to use same keycode as before in case of rotation
2365 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2366 } else {
2367 // key down
2368 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2369 && mContext->shouldDropVirtualKey(when,
2370 getDevice(), keyCode, scanCode)) {
2371 return;
2372 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002373 if (policyFlags & POLICY_FLAG_GESTURE) {
2374 mDevice->cancelTouch(when);
2375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376
2377 mKeyDowns.push();
2378 KeyDown& keyDown = mKeyDowns.editTop();
2379 keyDown.keyCode = keyCode;
2380 keyDown.scanCode = scanCode;
2381 }
2382
2383 mDownTime = when;
2384 } else {
2385 // Remove key down.
2386 ssize_t keyDownIndex = findKeyDown(scanCode);
2387 if (keyDownIndex >= 0) {
2388 // key up, be sure to use same keycode as before in case of rotation
2389 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2390 mKeyDowns.removeAt(size_t(keyDownIndex));
2391 } else {
2392 // key was not actually down
2393 ALOGI("Dropping key up from device %s because the key was not down. "
2394 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002395 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 return;
2397 }
2398 }
2399
Andrii Kulian763a3a42016-03-08 10:46:16 -08002400 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002401 // If global meta state changed send it along with the key.
2402 // If it has not changed then we'll use what keymap gave us,
2403 // since key replacement logic might temporarily reset a few
2404 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002405 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
2407
2408 nsecs_t downTime = mDownTime;
2409
2410 // Key down on external an keyboard should wake the device.
2411 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2412 // For internal keyboards, the key layout file should specify the policy flags for
2413 // each wake key individually.
2414 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002415 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002416 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002419 if (mParameters.handlesKeyRepeat) {
2420 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2421 }
2422
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002423 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002425 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 getListener()->notifyKey(&args);
2427}
2428
2429ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2430 size_t n = mKeyDowns.size();
2431 for (size_t i = 0; i < n; i++) {
2432 if (mKeyDowns[i].scanCode == scanCode) {
2433 return i;
2434 }
2435 }
2436 return -1;
2437}
2438
2439int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2440 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2441}
2442
2443int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2444 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2445}
2446
2447bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2448 const int32_t* keyCodes, uint8_t* outFlags) {
2449 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2450}
2451
2452int32_t KeyboardInputMapper::getMetaState() {
2453 return mMetaState;
2454}
2455
Andrii Kulian763a3a42016-03-08 10:46:16 -08002456void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2457 updateMetaStateIfNeeded(keyCode, false);
2458}
2459
2460bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2461 int32_t oldMetaState = mMetaState;
2462 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2463 bool metaStateChanged = oldMetaState != newMetaState;
2464 if (metaStateChanged) {
2465 mMetaState = newMetaState;
2466 updateLedState(false);
2467
2468 getContext()->updateGlobalMetaState();
2469 }
2470
2471 return metaStateChanged;
2472}
2473
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474void KeyboardInputMapper::resetLedState() {
2475 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2476 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2477 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2478
2479 updateLedState(true);
2480}
2481
2482void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2483 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2484 ledState.on = false;
2485}
2486
2487void KeyboardInputMapper::updateLedState(bool reset) {
2488 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2489 AMETA_CAPS_LOCK_ON, reset);
2490 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2491 AMETA_NUM_LOCK_ON, reset);
2492 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2493 AMETA_SCROLL_LOCK_ON, reset);
2494}
2495
2496void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2497 int32_t led, int32_t modifier, bool reset) {
2498 if (ledState.avail) {
2499 bool desiredState = (mMetaState & modifier) != 0;
2500 if (reset || ledState.on != desiredState) {
2501 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2502 ledState.on = desiredState;
2503 }
2504 }
2505}
2506
2507
2508// --- CursorInputMapper ---
2509
2510CursorInputMapper::CursorInputMapper(InputDevice* device) :
2511 InputMapper(device) {
2512}
2513
2514CursorInputMapper::~CursorInputMapper() {
2515}
2516
2517uint32_t CursorInputMapper::getSources() {
2518 return mSource;
2519}
2520
2521void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2522 InputMapper::populateDeviceInfo(info);
2523
2524 if (mParameters.mode == Parameters::MODE_POINTER) {
2525 float minX, minY, maxX, maxY;
2526 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2527 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2528 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2529 }
2530 } else {
2531 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2532 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2533 }
2534 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2535
2536 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2537 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2538 }
2539 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2540 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2541 }
2542}
2543
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002544void CursorInputMapper::dump(std::string& dump) {
2545 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002547 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2548 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2549 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2550 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2551 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002553 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002555 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2556 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2557 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2558 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2559 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2560 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561}
2562
2563void CursorInputMapper::configure(nsecs_t when,
2564 const InputReaderConfiguration* config, uint32_t changes) {
2565 InputMapper::configure(when, config, changes);
2566
2567 if (!changes) { // first time only
2568 mCursorScrollAccumulator.configure(getDevice());
2569
2570 // Configure basic parameters.
2571 configureParameters();
2572
2573 // Configure device mode.
2574 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002575 case Parameters::MODE_POINTER_RELATIVE:
2576 // Should not happen during first time configuration.
2577 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2578 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002579 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 case Parameters::MODE_POINTER:
2581 mSource = AINPUT_SOURCE_MOUSE;
2582 mXPrecision = 1.0f;
2583 mYPrecision = 1.0f;
2584 mXScale = 1.0f;
2585 mYScale = 1.0f;
2586 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2587 break;
2588 case Parameters::MODE_NAVIGATION:
2589 mSource = AINPUT_SOURCE_TRACKBALL;
2590 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2591 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2592 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2593 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2594 break;
2595 }
2596
2597 mVWheelScale = 1.0f;
2598 mHWheelScale = 1.0f;
2599 }
2600
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002601 if ((!changes && config->pointerCapture)
2602 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2603 if (config->pointerCapture) {
2604 if (mParameters.mode == Parameters::MODE_POINTER) {
2605 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2606 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2607 // Keep PointerController around in order to preserve the pointer position.
2608 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2609 } else {
2610 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2611 }
2612 } else {
2613 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2614 mParameters.mode = Parameters::MODE_POINTER;
2615 mSource = AINPUT_SOURCE_MOUSE;
2616 } else {
2617 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2618 }
2619 }
2620 bumpGeneration();
2621 if (changes) {
2622 getDevice()->notifyReset(when);
2623 }
2624 }
2625
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2627 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2628 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2629 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2630 }
2631
2632 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002633 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002635 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002636 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002637 if (internalViewport) {
2638 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640 }
Andrii Kulian620f6d92018-09-14 16:51:59 -07002641 getPolicy()->updatePointerDisplay();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 bumpGeneration();
2643 }
2644}
2645
2646void CursorInputMapper::configureParameters() {
2647 mParameters.mode = Parameters::MODE_POINTER;
2648 String8 cursorModeString;
2649 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2650 if (cursorModeString == "navigation") {
2651 mParameters.mode = Parameters::MODE_NAVIGATION;
2652 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2653 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2654 }
2655 }
2656
2657 mParameters.orientationAware = false;
2658 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2659 mParameters.orientationAware);
2660
2661 mParameters.hasAssociatedDisplay = false;
2662 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2663 mParameters.hasAssociatedDisplay = true;
2664 }
2665}
2666
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002667void CursorInputMapper::dumpParameters(std::string& dump) {
2668 dump += INDENT3 "Parameters:\n";
2669 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 toString(mParameters.hasAssociatedDisplay));
2671
2672 switch (mParameters.mode) {
2673 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002674 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002675 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002676 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002677 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002678 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002680 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 break;
2682 default:
2683 ALOG_ASSERT(false);
2684 }
2685
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002686 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002687 toString(mParameters.orientationAware));
2688}
2689
2690void CursorInputMapper::reset(nsecs_t when) {
2691 mButtonState = 0;
2692 mDownTime = 0;
2693
2694 mPointerVelocityControl.reset();
2695 mWheelXVelocityControl.reset();
2696 mWheelYVelocityControl.reset();
2697
2698 mCursorButtonAccumulator.reset(getDevice());
2699 mCursorMotionAccumulator.reset(getDevice());
2700 mCursorScrollAccumulator.reset(getDevice());
2701
2702 InputMapper::reset(when);
2703}
2704
2705void CursorInputMapper::process(const RawEvent* rawEvent) {
2706 mCursorButtonAccumulator.process(rawEvent);
2707 mCursorMotionAccumulator.process(rawEvent);
2708 mCursorScrollAccumulator.process(rawEvent);
2709
2710 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2711 sync(rawEvent->when);
2712 }
2713}
2714
2715void CursorInputMapper::sync(nsecs_t when) {
2716 int32_t lastButtonState = mButtonState;
2717 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2718 mButtonState = currentButtonState;
2719
2720 bool wasDown = isPointerDown(lastButtonState);
2721 bool down = isPointerDown(currentButtonState);
2722 bool downChanged;
2723 if (!wasDown && down) {
2724 mDownTime = when;
2725 downChanged = true;
2726 } else if (wasDown && !down) {
2727 downChanged = true;
2728 } else {
2729 downChanged = false;
2730 }
2731 nsecs_t downTime = mDownTime;
2732 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002733 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2734 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002735
2736 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2737 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2738 bool moved = deltaX != 0 || deltaY != 0;
2739
2740 // Rotate delta according to orientation if needed.
2741 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2742 && (deltaX != 0.0f || deltaY != 0.0f)) {
2743 rotateDelta(mOrientation, &deltaX, &deltaY);
2744 }
2745
2746 // Move the pointer.
2747 PointerProperties pointerProperties;
2748 pointerProperties.clear();
2749 pointerProperties.id = 0;
2750 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2751
2752 PointerCoords pointerCoords;
2753 pointerCoords.clear();
2754
2755 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2756 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2757 bool scrolled = vscroll != 0 || hscroll != 0;
2758
Yi Kong9b14ac62018-07-17 13:48:38 -07002759 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2760 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002761
2762 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2763
2764 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002765 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 if (moved || scrolled || buttonsChanged) {
2767 mPointerController->setPresentation(
2768 PointerControllerInterface::PRESENTATION_POINTER);
2769
2770 if (moved) {
2771 mPointerController->move(deltaX, deltaY);
2772 }
2773
2774 if (buttonsChanged) {
2775 mPointerController->setButtonState(currentButtonState);
2776 }
2777
2778 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2779 }
2780
2781 float x, y;
2782 mPointerController->getPosition(&x, &y);
2783 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2784 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002785 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2786 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Andrii Kulian620f6d92018-09-14 16:51:59 -07002787 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 } else {
2789 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2790 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2791 displayId = ADISPLAY_ID_NONE;
2792 }
2793
2794 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2795
2796 // Moving an external trackball or mouse should wake the device.
2797 // We don't do this for internal cursor devices to prevent them from waking up
2798 // the device in your pocket.
2799 // TODO: Use the input device configuration to control this behavior more finely.
2800 uint32_t policyFlags = 0;
2801 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002802 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002803 }
2804
2805 // Synthesize key down from buttons if needed.
2806 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002807 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808
2809 // Send motion event.
2810 if (downChanged || moved || scrolled || buttonsChanged) {
2811 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002812 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 int32_t motionEventAction;
2814 if (downChanged) {
2815 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002816 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2818 } else {
2819 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2820 }
2821
Michael Wright7b159c92015-05-14 14:48:03 +01002822 if (buttonsReleased) {
2823 BitSet32 released(buttonsReleased);
2824 while (!released.isEmpty()) {
2825 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2826 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002827 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002828 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2829 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002830 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002831 mXPrecision, mYPrecision, downTime);
2832 getListener()->notifyMotion(&releaseArgs);
2833 }
2834 }
2835
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002836 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002837 motionEventAction, 0, 0, metaState, currentButtonState,
2838 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002839 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002840 mXPrecision, mYPrecision, downTime);
2841 getListener()->notifyMotion(&args);
2842
Michael Wright7b159c92015-05-14 14:48:03 +01002843 if (buttonsPressed) {
2844 BitSet32 pressed(buttonsPressed);
2845 while (!pressed.isEmpty()) {
2846 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2847 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002848 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002849 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2850 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002851 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002852 mXPrecision, mYPrecision, downTime);
2853 getListener()->notifyMotion(&pressArgs);
2854 }
2855 }
2856
2857 ALOG_ASSERT(buttonState == currentButtonState);
2858
Michael Wrightd02c5b62014-02-10 15:10:22 -08002859 // Send hover move after UP to tell the application that the mouse is hovering now.
2860 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002861 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002862 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002863 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002865 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 mXPrecision, mYPrecision, downTime);
2867 getListener()->notifyMotion(&hoverArgs);
2868 }
2869
2870 // Send scroll events.
2871 if (scrolled) {
2872 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2873 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2874
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002875 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002876 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002877 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002878 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 mXPrecision, mYPrecision, downTime);
2880 getListener()->notifyMotion(&scrollArgs);
2881 }
2882 }
2883
2884 // Synthesize key up from buttons if needed.
2885 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002886 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887
2888 mCursorMotionAccumulator.finishSync();
2889 mCursorScrollAccumulator.finishSync();
2890}
2891
2892int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2893 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2894 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2895 } else {
2896 return AKEY_STATE_UNKNOWN;
2897 }
2898}
2899
2900void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002901 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002902 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2903 }
2904}
2905
Prashant Malani1941ff52015-08-11 18:29:28 -07002906// --- RotaryEncoderInputMapper ---
2907
2908RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002909 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002910 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2911}
2912
2913RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2914}
2915
2916uint32_t RotaryEncoderInputMapper::getSources() {
2917 return mSource;
2918}
2919
2920void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2921 InputMapper::populateDeviceInfo(info);
2922
2923 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002924 float res = 0.0f;
2925 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2926 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2927 }
2928 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2929 mScalingFactor)) {
2930 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2931 "default to 1.0!\n");
2932 mScalingFactor = 1.0f;
2933 }
2934 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2935 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002936 }
2937}
2938
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002939void RotaryEncoderInputMapper::dump(std::string& dump) {
2940 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2941 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002942 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2943}
2944
2945void RotaryEncoderInputMapper::configure(nsecs_t when,
2946 const InputReaderConfiguration* config, uint32_t changes) {
2947 InputMapper::configure(when, config, changes);
2948 if (!changes) {
2949 mRotaryEncoderScrollAccumulator.configure(getDevice());
2950 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002951 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002952 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002953 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002954 if (internalViewport) {
2955 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002956 } else {
2957 mOrientation = DISPLAY_ORIENTATION_0;
2958 }
2959 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002960}
2961
2962void RotaryEncoderInputMapper::reset(nsecs_t when) {
2963 mRotaryEncoderScrollAccumulator.reset(getDevice());
2964
2965 InputMapper::reset(when);
2966}
2967
2968void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2969 mRotaryEncoderScrollAccumulator.process(rawEvent);
2970
2971 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2972 sync(rawEvent->when);
2973 }
2974}
2975
2976void RotaryEncoderInputMapper::sync(nsecs_t when) {
2977 PointerCoords pointerCoords;
2978 pointerCoords.clear();
2979
2980 PointerProperties pointerProperties;
2981 pointerProperties.clear();
2982 pointerProperties.id = 0;
2983 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2984
2985 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2986 bool scrolled = scroll != 0;
2987
2988 // This is not a pointer, so it's not associated with a display.
2989 int32_t displayId = ADISPLAY_ID_NONE;
2990
2991 // Moving the rotary encoder should wake the device (if specified).
2992 uint32_t policyFlags = 0;
2993 if (scrolled && getDevice()->isExternal()) {
2994 policyFlags |= POLICY_FLAG_WAKE;
2995 }
2996
Ivan Podogovad437252016-09-29 16:29:55 +01002997 if (mOrientation == DISPLAY_ORIENTATION_180) {
2998 scroll = -scroll;
2999 }
3000
Prashant Malani1941ff52015-08-11 18:29:28 -07003001 // Send motion event.
3002 if (scrolled) {
3003 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003004 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003005
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003006 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003007 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3008 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003009 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003010 0, 0, 0);
3011 getListener()->notifyMotion(&scrollArgs);
3012 }
3013
3014 mRotaryEncoderScrollAccumulator.finishSync();
3015}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003016
3017// --- TouchInputMapper ---
3018
3019TouchInputMapper::TouchInputMapper(InputDevice* device) :
3020 InputMapper(device),
3021 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3022 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003023 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003024 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3025}
3026
3027TouchInputMapper::~TouchInputMapper() {
3028}
3029
3030uint32_t TouchInputMapper::getSources() {
3031 return mSource;
3032}
3033
3034void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3035 InputMapper::populateDeviceInfo(info);
3036
3037 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3038 info->addMotionRange(mOrientedRanges.x);
3039 info->addMotionRange(mOrientedRanges.y);
3040 info->addMotionRange(mOrientedRanges.pressure);
3041
3042 if (mOrientedRanges.haveSize) {
3043 info->addMotionRange(mOrientedRanges.size);
3044 }
3045
3046 if (mOrientedRanges.haveTouchSize) {
3047 info->addMotionRange(mOrientedRanges.touchMajor);
3048 info->addMotionRange(mOrientedRanges.touchMinor);
3049 }
3050
3051 if (mOrientedRanges.haveToolSize) {
3052 info->addMotionRange(mOrientedRanges.toolMajor);
3053 info->addMotionRange(mOrientedRanges.toolMinor);
3054 }
3055
3056 if (mOrientedRanges.haveOrientation) {
3057 info->addMotionRange(mOrientedRanges.orientation);
3058 }
3059
3060 if (mOrientedRanges.haveDistance) {
3061 info->addMotionRange(mOrientedRanges.distance);
3062 }
3063
3064 if (mOrientedRanges.haveTilt) {
3065 info->addMotionRange(mOrientedRanges.tilt);
3066 }
3067
3068 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3069 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3070 0.0f);
3071 }
3072 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3073 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3074 0.0f);
3075 }
3076 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3077 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3078 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3079 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3080 x.fuzz, x.resolution);
3081 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3082 y.fuzz, y.resolution);
3083 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3084 x.fuzz, x.resolution);
3085 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3086 y.fuzz, y.resolution);
3087 }
3088 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3089 }
3090}
3091
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003092void TouchInputMapper::dump(std::string& dump) {
3093 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003094 dumpParameters(dump);
3095 dumpVirtualKeys(dump);
3096 dumpRawPointerAxes(dump);
3097 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003098 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 dumpSurface(dump);
3100
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003101 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3102 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3103 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3104 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3105 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3106 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3107 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3108 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3109 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3110 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3111 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3112 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3113 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3114 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3115 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3116 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3117 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003119 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3120 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003121 mLastRawState.rawPointerData.pointerCount);
3122 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3123 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003124 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3126 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3127 "toolType=%d, isHovering=%s\n", i,
3128 pointer.id, pointer.x, pointer.y, pointer.pressure,
3129 pointer.touchMajor, pointer.touchMinor,
3130 pointer.toolMajor, pointer.toolMinor,
3131 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3132 pointer.toolType, toString(pointer.isHovering));
3133 }
3134
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003135 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3136 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003137 mLastCookedState.cookedPointerData.pointerCount);
3138 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3139 const PointerProperties& pointerProperties =
3140 mLastCookedState.cookedPointerData.pointerProperties[i];
3141 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003142 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3144 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3145 "toolType=%d, isHovering=%s\n", i,
3146 pointerProperties.id,
3147 pointerCoords.getX(),
3148 pointerCoords.getY(),
3149 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3150 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3151 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3152 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3153 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3154 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3155 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3156 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3157 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003158 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003159 }
3160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003161 dump += INDENT3 "Stylus Fusion:\n";
3162 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003163 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003164 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3165 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003166 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003167 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003168 dumpStylusState(dump, mExternalStylusState);
3169
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003171 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3172 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003173 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003176 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003178 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003180 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003181 mPointerGestureMaxSwipeWidth);
3182 }
3183}
3184
Santos Cordonfa5cf462017-04-05 10:37:00 -07003185const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3186 switch (deviceMode) {
3187 case DEVICE_MODE_DISABLED:
3188 return "disabled";
3189 case DEVICE_MODE_DIRECT:
3190 return "direct";
3191 case DEVICE_MODE_UNSCALED:
3192 return "unscaled";
3193 case DEVICE_MODE_NAVIGATION:
3194 return "navigation";
3195 case DEVICE_MODE_POINTER:
3196 return "pointer";
3197 }
3198 return "unknown";
3199}
3200
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201void TouchInputMapper::configure(nsecs_t when,
3202 const InputReaderConfiguration* config, uint32_t changes) {
3203 InputMapper::configure(when, config, changes);
3204
3205 mConfig = *config;
3206
3207 if (!changes) { // first time only
3208 // Configure basic parameters.
3209 configureParameters();
3210
3211 // Configure common accumulators.
3212 mCursorScrollAccumulator.configure(getDevice());
3213 mTouchButtonAccumulator.configure(getDevice());
3214
3215 // Configure absolute axis information.
3216 configureRawPointerAxes();
3217
3218 // Prepare input device calibration.
3219 parseCalibration();
3220 resolveCalibration();
3221 }
3222
Michael Wright842500e2015-03-13 17:32:02 -07003223 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003224 // Update location calibration to reflect current settings
3225 updateAffineTransformation();
3226 }
3227
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3229 // Update pointer speed.
3230 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3231 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3232 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3233 }
3234
3235 bool resetNeeded = false;
3236 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3237 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003238 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3239 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240 // Configure device sources, surface dimensions, orientation and
3241 // scaling factors.
3242 configureSurface(when, &resetNeeded);
3243 }
3244
3245 if (changes && resetNeeded) {
3246 // Send reset, unless this is the first time the device has been configured,
3247 // in which case the reader will call reset itself after all mappers are ready.
3248 getDevice()->notifyReset(when);
3249 }
3250}
3251
Michael Wright842500e2015-03-13 17:32:02 -07003252void TouchInputMapper::resolveExternalStylusPresence() {
3253 Vector<InputDeviceInfo> devices;
3254 mContext->getExternalStylusDevices(devices);
3255 mExternalStylusConnected = !devices.isEmpty();
3256
3257 if (!mExternalStylusConnected) {
3258 resetExternalStylus();
3259 }
3260}
3261
Michael Wrightd02c5b62014-02-10 15:10:22 -08003262void TouchInputMapper::configureParameters() {
3263 // Use the pointer presentation mode for devices that do not support distinct
3264 // multitouch. The spot-based presentation relies on being able to accurately
3265 // locate two or more fingers on the touch pad.
3266 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003267 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003268
3269 String8 gestureModeString;
3270 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3271 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003272 if (gestureModeString == "single-touch") {
3273 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3274 } else if (gestureModeString == "multi-touch") {
3275 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003276 } else if (gestureModeString != "default") {
3277 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3278 }
3279 }
3280
3281 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3282 // The device is a touch screen.
3283 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3284 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3285 // The device is a pointing device like a track pad.
3286 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3287 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3288 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3289 // The device is a cursor device with a touch pad attached.
3290 // By default don't use the touch pad to move the pointer.
3291 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3292 } else {
3293 // The device is a touch pad of unknown purpose.
3294 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3295 }
3296
3297 mParameters.hasButtonUnderPad=
3298 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3299
3300 String8 deviceTypeString;
3301 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3302 deviceTypeString)) {
3303 if (deviceTypeString == "touchScreen") {
3304 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3305 } else if (deviceTypeString == "touchPad") {
3306 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3307 } else if (deviceTypeString == "touchNavigation") {
3308 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3309 } else if (deviceTypeString == "pointer") {
3310 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3311 } else if (deviceTypeString != "default") {
3312 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3313 }
3314 }
3315
3316 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3317 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3318 mParameters.orientationAware);
3319
3320 mParameters.hasAssociatedDisplay = false;
3321 mParameters.associatedDisplayIsExternal = false;
3322 if (mParameters.orientationAware
3323 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3324 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3325 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003326 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3327 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003328 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003329 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003330 uniqueDisplayId);
3331 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003332 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003333 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003334 if (getDevice()->getAssociatedDisplayPort()) {
3335 mParameters.hasAssociatedDisplay = true;
3336 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003337
3338 // Initial downs on external touch devices should wake the device.
3339 // Normally we don't do this for internal touch screens to prevent them from waking
3340 // up in your pocket but you can enable it using the input device configuration.
3341 mParameters.wake = getDevice()->isExternal();
3342 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3343 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003344}
3345
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003346void TouchInputMapper::dumpParameters(std::string& dump) {
3347 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348
3349 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003350 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003351 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003352 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003353 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003354 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 break;
3356 default:
3357 assert(false);
3358 }
3359
3360 switch (mParameters.deviceType) {
3361 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003362 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003363 break;
3364 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003365 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003366 break;
3367 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003368 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 break;
3370 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003371 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 break;
3373 default:
3374 ALOG_ASSERT(false);
3375 }
3376
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003377 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003378 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003380 toString(mParameters.associatedDisplayIsExternal),
3381 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 toString(mParameters.orientationAware));
3384}
3385
3386void TouchInputMapper::configureRawPointerAxes() {
3387 mRawPointerAxes.clear();
3388}
3389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3391 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3393 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3394 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3395 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3396 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3397 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3398 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3399 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3400 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3401 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3402 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3403 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3404 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3405}
3406
Michael Wright842500e2015-03-13 17:32:02 -07003407bool TouchInputMapper::hasExternalStylus() const {
3408 return mExternalStylusConnected;
3409}
3410
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003411/**
3412 * Determine which DisplayViewport to use.
3413 * 1. If display port is specified, return the matching viewport. If matching viewport not
3414 * found, then return.
3415 * 2. If a device has associated display, get the matching viewport by either unique id or by
3416 * the display type (internal or external).
3417 * 3. Otherwise, use a non-display viewport.
3418 */
3419std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3420 if (mParameters.hasAssociatedDisplay) {
3421 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3422 if (displayPort) {
3423 // Find the viewport that contains the same port
3424 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3425 if (!v) {
3426 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3427 "but the corresponding viewport is not found.",
3428 getDeviceName().c_str(), *displayPort);
3429 }
3430 return v;
3431 }
3432
3433 if (!mParameters.uniqueDisplayId.empty()) {
3434 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3435 }
3436
3437 ViewportType viewportTypeToUse;
3438 if (mParameters.associatedDisplayIsExternal) {
3439 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3440 } else {
3441 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3442 }
3443 return mConfig.getDisplayViewportByType(viewportTypeToUse);
3444 }
3445
3446 DisplayViewport newViewport;
3447 // Raw width and height in the natural orientation.
3448 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3449 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3450 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3451 return std::make_optional(newViewport);
3452}
3453
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3455 int32_t oldDeviceMode = mDeviceMode;
3456
Michael Wright842500e2015-03-13 17:32:02 -07003457 resolveExternalStylusPresence();
3458
Michael Wrightd02c5b62014-02-10 15:10:22 -08003459 // Determine device mode.
3460 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3461 && mConfig.pointerGesturesEnabled) {
3462 mSource = AINPUT_SOURCE_MOUSE;
3463 mDeviceMode = DEVICE_MODE_POINTER;
3464 if (hasStylus()) {
3465 mSource |= AINPUT_SOURCE_STYLUS;
3466 }
3467 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3468 && mParameters.hasAssociatedDisplay) {
3469 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3470 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003471 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003472 mSource |= AINPUT_SOURCE_STYLUS;
3473 }
Michael Wright2f78b682015-06-12 15:25:08 +01003474 if (hasExternalStylus()) {
3475 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3476 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3478 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3479 mDeviceMode = DEVICE_MODE_NAVIGATION;
3480 } else {
3481 mSource = AINPUT_SOURCE_TOUCHPAD;
3482 mDeviceMode = DEVICE_MODE_UNSCALED;
3483 }
3484
3485 // Ensure we have valid X and Y axes.
3486 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003487 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003488 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003489 mDeviceMode = DEVICE_MODE_DISABLED;
3490 return;
3491 }
3492
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003493 // Get associated display dimensions.
3494 std::optional<DisplayViewport> newViewport = findViewport();
3495 if (!newViewport) {
3496 ALOGI("Touch device '%s' could not query the properties of its associated "
3497 "display. The device will be inoperable until the display size "
3498 "becomes available.",
3499 getDeviceName().c_str());
3500 mDeviceMode = DEVICE_MODE_DISABLED;
3501 return;
3502 }
3503
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003505 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3506 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003507
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003508 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003510 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511
3512 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3513 // Convert rotated viewport to natural surface coordinates.
3514 int32_t naturalLogicalWidth, naturalLogicalHeight;
3515 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3516 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3517 int32_t naturalDeviceWidth, naturalDeviceHeight;
3518 switch (mViewport.orientation) {
3519 case DISPLAY_ORIENTATION_90:
3520 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3521 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3522 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3523 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3524 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3525 naturalPhysicalTop = mViewport.physicalLeft;
3526 naturalDeviceWidth = mViewport.deviceHeight;
3527 naturalDeviceHeight = mViewport.deviceWidth;
3528 break;
3529 case DISPLAY_ORIENTATION_180:
3530 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3531 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3532 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3533 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3534 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3535 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3536 naturalDeviceWidth = mViewport.deviceWidth;
3537 naturalDeviceHeight = mViewport.deviceHeight;
3538 break;
3539 case DISPLAY_ORIENTATION_270:
3540 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3541 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3542 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3543 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3544 naturalPhysicalLeft = mViewport.physicalTop;
3545 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3546 naturalDeviceWidth = mViewport.deviceHeight;
3547 naturalDeviceHeight = mViewport.deviceWidth;
3548 break;
3549 case DISPLAY_ORIENTATION_0:
3550 default:
3551 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3552 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3553 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3554 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3555 naturalPhysicalLeft = mViewport.physicalLeft;
3556 naturalPhysicalTop = mViewport.physicalTop;
3557 naturalDeviceWidth = mViewport.deviceWidth;
3558 naturalDeviceHeight = mViewport.deviceHeight;
3559 break;
3560 }
3561
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003562 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3563 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3564 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3565 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3566 }
3567
Michael Wright358bcc72018-08-21 04:01:07 +01003568 mPhysicalWidth = naturalPhysicalWidth;
3569 mPhysicalHeight = naturalPhysicalHeight;
3570 mPhysicalLeft = naturalPhysicalLeft;
3571 mPhysicalTop = naturalPhysicalTop;
3572
Michael Wrightd02c5b62014-02-10 15:10:22 -08003573 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3574 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3575 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3576 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3577
3578 mSurfaceOrientation = mParameters.orientationAware ?
3579 mViewport.orientation : DISPLAY_ORIENTATION_0;
3580 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003581 mPhysicalWidth = rawWidth;
3582 mPhysicalHeight = rawHeight;
3583 mPhysicalLeft = 0;
3584 mPhysicalTop = 0;
3585
Michael Wrightd02c5b62014-02-10 15:10:22 -08003586 mSurfaceWidth = rawWidth;
3587 mSurfaceHeight = rawHeight;
3588 mSurfaceLeft = 0;
3589 mSurfaceTop = 0;
3590 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3591 }
3592 }
3593
3594 // If moving between pointer modes, need to reset some state.
3595 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3596 if (deviceModeChanged) {
3597 mOrientedRanges.clear();
3598 }
3599
3600 // Create pointer controller if needed.
3601 if (mDeviceMode == DEVICE_MODE_POINTER ||
3602 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003603 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003604 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
Andrii Kulian620f6d92018-09-14 16:51:59 -07003605 getPolicy()->updatePointerDisplay();
3606 } else if (viewportChanged) {
3607 getPolicy()->updatePointerDisplay();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003608 }
3609 } else {
3610 mPointerController.clear();
3611 }
3612
3613 if (viewportChanged || deviceModeChanged) {
3614 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3615 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003616 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3618
3619 // Configure X and Y factors.
3620 mXScale = float(mSurfaceWidth) / rawWidth;
3621 mYScale = float(mSurfaceHeight) / rawHeight;
3622 mXTranslate = -mSurfaceLeft;
3623 mYTranslate = -mSurfaceTop;
3624 mXPrecision = 1.0f / mXScale;
3625 mYPrecision = 1.0f / mYScale;
3626
3627 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3628 mOrientedRanges.x.source = mSource;
3629 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3630 mOrientedRanges.y.source = mSource;
3631
3632 configureVirtualKeys();
3633
3634 // Scale factor for terms that are not oriented in a particular axis.
3635 // If the pixels are square then xScale == yScale otherwise we fake it
3636 // by choosing an average.
3637 mGeometricScale = avg(mXScale, mYScale);
3638
3639 // Size of diagonal axis.
3640 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3641
3642 // Size factors.
3643 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3644 if (mRawPointerAxes.touchMajor.valid
3645 && mRawPointerAxes.touchMajor.maxValue != 0) {
3646 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3647 } else if (mRawPointerAxes.toolMajor.valid
3648 && mRawPointerAxes.toolMajor.maxValue != 0) {
3649 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3650 } else {
3651 mSizeScale = 0.0f;
3652 }
3653
3654 mOrientedRanges.haveTouchSize = true;
3655 mOrientedRanges.haveToolSize = true;
3656 mOrientedRanges.haveSize = true;
3657
3658 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3659 mOrientedRanges.touchMajor.source = mSource;
3660 mOrientedRanges.touchMajor.min = 0;
3661 mOrientedRanges.touchMajor.max = diagonalSize;
3662 mOrientedRanges.touchMajor.flat = 0;
3663 mOrientedRanges.touchMajor.fuzz = 0;
3664 mOrientedRanges.touchMajor.resolution = 0;
3665
3666 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3667 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3668
3669 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3670 mOrientedRanges.toolMajor.source = mSource;
3671 mOrientedRanges.toolMajor.min = 0;
3672 mOrientedRanges.toolMajor.max = diagonalSize;
3673 mOrientedRanges.toolMajor.flat = 0;
3674 mOrientedRanges.toolMajor.fuzz = 0;
3675 mOrientedRanges.toolMajor.resolution = 0;
3676
3677 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3678 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3679
3680 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3681 mOrientedRanges.size.source = mSource;
3682 mOrientedRanges.size.min = 0;
3683 mOrientedRanges.size.max = 1.0;
3684 mOrientedRanges.size.flat = 0;
3685 mOrientedRanges.size.fuzz = 0;
3686 mOrientedRanges.size.resolution = 0;
3687 } else {
3688 mSizeScale = 0.0f;
3689 }
3690
3691 // Pressure factors.
3692 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003693 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3695 || mCalibration.pressureCalibration
3696 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3697 if (mCalibration.havePressureScale) {
3698 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003699 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003700 } else if (mRawPointerAxes.pressure.valid
3701 && mRawPointerAxes.pressure.maxValue != 0) {
3702 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3703 }
3704 }
3705
3706 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3707 mOrientedRanges.pressure.source = mSource;
3708 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003709 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003710 mOrientedRanges.pressure.flat = 0;
3711 mOrientedRanges.pressure.fuzz = 0;
3712 mOrientedRanges.pressure.resolution = 0;
3713
3714 // Tilt
3715 mTiltXCenter = 0;
3716 mTiltXScale = 0;
3717 mTiltYCenter = 0;
3718 mTiltYScale = 0;
3719 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3720 if (mHaveTilt) {
3721 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3722 mRawPointerAxes.tiltX.maxValue);
3723 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3724 mRawPointerAxes.tiltY.maxValue);
3725 mTiltXScale = M_PI / 180;
3726 mTiltYScale = M_PI / 180;
3727
3728 mOrientedRanges.haveTilt = true;
3729
3730 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3731 mOrientedRanges.tilt.source = mSource;
3732 mOrientedRanges.tilt.min = 0;
3733 mOrientedRanges.tilt.max = M_PI_2;
3734 mOrientedRanges.tilt.flat = 0;
3735 mOrientedRanges.tilt.fuzz = 0;
3736 mOrientedRanges.tilt.resolution = 0;
3737 }
3738
3739 // Orientation
3740 mOrientationScale = 0;
3741 if (mHaveTilt) {
3742 mOrientedRanges.haveOrientation = true;
3743
3744 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3745 mOrientedRanges.orientation.source = mSource;
3746 mOrientedRanges.orientation.min = -M_PI;
3747 mOrientedRanges.orientation.max = M_PI;
3748 mOrientedRanges.orientation.flat = 0;
3749 mOrientedRanges.orientation.fuzz = 0;
3750 mOrientedRanges.orientation.resolution = 0;
3751 } else if (mCalibration.orientationCalibration !=
3752 Calibration::ORIENTATION_CALIBRATION_NONE) {
3753 if (mCalibration.orientationCalibration
3754 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3755 if (mRawPointerAxes.orientation.valid) {
3756 if (mRawPointerAxes.orientation.maxValue > 0) {
3757 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3758 } else if (mRawPointerAxes.orientation.minValue < 0) {
3759 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3760 } else {
3761 mOrientationScale = 0;
3762 }
3763 }
3764 }
3765
3766 mOrientedRanges.haveOrientation = true;
3767
3768 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3769 mOrientedRanges.orientation.source = mSource;
3770 mOrientedRanges.orientation.min = -M_PI_2;
3771 mOrientedRanges.orientation.max = M_PI_2;
3772 mOrientedRanges.orientation.flat = 0;
3773 mOrientedRanges.orientation.fuzz = 0;
3774 mOrientedRanges.orientation.resolution = 0;
3775 }
3776
3777 // Distance
3778 mDistanceScale = 0;
3779 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3780 if (mCalibration.distanceCalibration
3781 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3782 if (mCalibration.haveDistanceScale) {
3783 mDistanceScale = mCalibration.distanceScale;
3784 } else {
3785 mDistanceScale = 1.0f;
3786 }
3787 }
3788
3789 mOrientedRanges.haveDistance = true;
3790
3791 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3792 mOrientedRanges.distance.source = mSource;
3793 mOrientedRanges.distance.min =
3794 mRawPointerAxes.distance.minValue * mDistanceScale;
3795 mOrientedRanges.distance.max =
3796 mRawPointerAxes.distance.maxValue * mDistanceScale;
3797 mOrientedRanges.distance.flat = 0;
3798 mOrientedRanges.distance.fuzz =
3799 mRawPointerAxes.distance.fuzz * mDistanceScale;
3800 mOrientedRanges.distance.resolution = 0;
3801 }
3802
3803 // Compute oriented precision, scales and ranges.
3804 // Note that the maximum value reported is an inclusive maximum value so it is one
3805 // unit less than the total width or height of surface.
3806 switch (mSurfaceOrientation) {
3807 case DISPLAY_ORIENTATION_90:
3808 case DISPLAY_ORIENTATION_270:
3809 mOrientedXPrecision = mYPrecision;
3810 mOrientedYPrecision = mXPrecision;
3811
3812 mOrientedRanges.x.min = mYTranslate;
3813 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3814 mOrientedRanges.x.flat = 0;
3815 mOrientedRanges.x.fuzz = 0;
3816 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3817
3818 mOrientedRanges.y.min = mXTranslate;
3819 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3820 mOrientedRanges.y.flat = 0;
3821 mOrientedRanges.y.fuzz = 0;
3822 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3823 break;
3824
3825 default:
3826 mOrientedXPrecision = mXPrecision;
3827 mOrientedYPrecision = mYPrecision;
3828
3829 mOrientedRanges.x.min = mXTranslate;
3830 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3831 mOrientedRanges.x.flat = 0;
3832 mOrientedRanges.x.fuzz = 0;
3833 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3834
3835 mOrientedRanges.y.min = mYTranslate;
3836 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3837 mOrientedRanges.y.flat = 0;
3838 mOrientedRanges.y.fuzz = 0;
3839 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3840 break;
3841 }
3842
Jason Gerecke71b16e82014-03-10 09:47:59 -07003843 // Location
3844 updateAffineTransformation();
3845
Michael Wrightd02c5b62014-02-10 15:10:22 -08003846 if (mDeviceMode == DEVICE_MODE_POINTER) {
3847 // Compute pointer gesture detection parameters.
3848 float rawDiagonal = hypotf(rawWidth, rawHeight);
3849 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3850
3851 // Scale movements such that one whole swipe of the touch pad covers a
3852 // given area relative to the diagonal size of the display when no acceleration
3853 // is applied.
3854 // Assume that the touch pad has a square aspect ratio such that movements in
3855 // X and Y of the same number of raw units cover the same physical distance.
3856 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3857 * displayDiagonal / rawDiagonal;
3858 mPointerYMovementScale = mPointerXMovementScale;
3859
3860 // Scale zooms to cover a smaller range of the display than movements do.
3861 // This value determines the area around the pointer that is affected by freeform
3862 // pointer gestures.
3863 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3864 * displayDiagonal / rawDiagonal;
3865 mPointerYZoomScale = mPointerXZoomScale;
3866
3867 // Max width between pointers to detect a swipe gesture is more than some fraction
3868 // of the diagonal axis of the touch pad. Touches that are wider than this are
3869 // translated into freeform gestures.
3870 mPointerGestureMaxSwipeWidth =
3871 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3872
3873 // Abort current pointer usages because the state has changed.
3874 abortPointerUsage(when, 0 /*policyFlags*/);
3875 }
3876
3877 // Inform the dispatcher about the changes.
3878 *outResetNeeded = true;
3879 bumpGeneration();
3880 }
3881}
3882
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003883void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003884 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003885 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3886 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3887 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3888 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003889 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3890 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3891 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3892 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003893 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003894}
3895
3896void TouchInputMapper::configureVirtualKeys() {
3897 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3898 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3899
3900 mVirtualKeys.clear();
3901
3902 if (virtualKeyDefinitions.size() == 0) {
3903 return;
3904 }
3905
3906 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3907
3908 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3909 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003910 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3911 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003912
3913 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3914 const VirtualKeyDefinition& virtualKeyDefinition =
3915 virtualKeyDefinitions[i];
3916
3917 mVirtualKeys.add();
3918 VirtualKey& virtualKey = mVirtualKeys.editTop();
3919
3920 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3921 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003922 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003923 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003924 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3925 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003926 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3927 virtualKey.scanCode);
3928 mVirtualKeys.pop(); // drop the key
3929 continue;
3930 }
3931
3932 virtualKey.keyCode = keyCode;
3933 virtualKey.flags = flags;
3934
3935 // convert the key definition's display coordinates into touch coordinates for a hit box
3936 int32_t halfWidth = virtualKeyDefinition.width / 2;
3937 int32_t halfHeight = virtualKeyDefinition.height / 2;
3938
3939 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3940 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3941 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3942 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3943 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3944 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3945 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3946 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3947 }
3948}
3949
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003950void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003952 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953
3954 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3955 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003956 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3958 i, virtualKey.scanCode, virtualKey.keyCode,
3959 virtualKey.hitLeft, virtualKey.hitRight,
3960 virtualKey.hitTop, virtualKey.hitBottom);
3961 }
3962 }
3963}
3964
3965void TouchInputMapper::parseCalibration() {
3966 const PropertyMap& in = getDevice()->getConfiguration();
3967 Calibration& out = mCalibration;
3968
3969 // Size
3970 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3971 String8 sizeCalibrationString;
3972 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3973 if (sizeCalibrationString == "none") {
3974 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3975 } else if (sizeCalibrationString == "geometric") {
3976 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3977 } else if (sizeCalibrationString == "diameter") {
3978 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3979 } else if (sizeCalibrationString == "box") {
3980 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3981 } else if (sizeCalibrationString == "area") {
3982 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3983 } else if (sizeCalibrationString != "default") {
3984 ALOGW("Invalid value for touch.size.calibration: '%s'",
3985 sizeCalibrationString.string());
3986 }
3987 }
3988
3989 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3990 out.sizeScale);
3991 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3992 out.sizeBias);
3993 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3994 out.sizeIsSummed);
3995
3996 // Pressure
3997 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3998 String8 pressureCalibrationString;
3999 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4000 if (pressureCalibrationString == "none") {
4001 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4002 } else if (pressureCalibrationString == "physical") {
4003 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4004 } else if (pressureCalibrationString == "amplitude") {
4005 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4006 } else if (pressureCalibrationString != "default") {
4007 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4008 pressureCalibrationString.string());
4009 }
4010 }
4011
4012 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4013 out.pressureScale);
4014
4015 // Orientation
4016 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4017 String8 orientationCalibrationString;
4018 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4019 if (orientationCalibrationString == "none") {
4020 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4021 } else if (orientationCalibrationString == "interpolated") {
4022 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4023 } else if (orientationCalibrationString == "vector") {
4024 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4025 } else if (orientationCalibrationString != "default") {
4026 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4027 orientationCalibrationString.string());
4028 }
4029 }
4030
4031 // Distance
4032 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4033 String8 distanceCalibrationString;
4034 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4035 if (distanceCalibrationString == "none") {
4036 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4037 } else if (distanceCalibrationString == "scaled") {
4038 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4039 } else if (distanceCalibrationString != "default") {
4040 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4041 distanceCalibrationString.string());
4042 }
4043 }
4044
4045 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4046 out.distanceScale);
4047
4048 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4049 String8 coverageCalibrationString;
4050 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4051 if (coverageCalibrationString == "none") {
4052 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4053 } else if (coverageCalibrationString == "box") {
4054 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4055 } else if (coverageCalibrationString != "default") {
4056 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4057 coverageCalibrationString.string());
4058 }
4059 }
4060}
4061
4062void TouchInputMapper::resolveCalibration() {
4063 // Size
4064 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4065 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4066 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4067 }
4068 } else {
4069 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4070 }
4071
4072 // Pressure
4073 if (mRawPointerAxes.pressure.valid) {
4074 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4075 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4076 }
4077 } else {
4078 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4079 }
4080
4081 // Orientation
4082 if (mRawPointerAxes.orientation.valid) {
4083 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4084 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4085 }
4086 } else {
4087 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4088 }
4089
4090 // Distance
4091 if (mRawPointerAxes.distance.valid) {
4092 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4093 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4094 }
4095 } else {
4096 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4097 }
4098
4099 // Coverage
4100 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4101 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4102 }
4103}
4104
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004105void TouchInputMapper::dumpCalibration(std::string& dump) {
4106 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004107
4108 // Size
4109 switch (mCalibration.sizeCalibration) {
4110 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004111 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004112 break;
4113 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004114 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004115 break;
4116 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004117 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 break;
4119 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004120 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 break;
4122 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004123 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 break;
4125 default:
4126 ALOG_ASSERT(false);
4127 }
4128
4129 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004130 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 mCalibration.sizeScale);
4132 }
4133
4134 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 mCalibration.sizeBias);
4137 }
4138
4139 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 toString(mCalibration.sizeIsSummed));
4142 }
4143
4144 // Pressure
4145 switch (mCalibration.pressureCalibration) {
4146 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 break;
4149 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 break;
4152 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004153 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154 break;
4155 default:
4156 ALOG_ASSERT(false);
4157 }
4158
4159 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 mCalibration.pressureScale);
4162 }
4163
4164 // Orientation
4165 switch (mCalibration.orientationCalibration) {
4166 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 break;
4169 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 break;
4172 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 break;
4175 default:
4176 ALOG_ASSERT(false);
4177 }
4178
4179 // Distance
4180 switch (mCalibration.distanceCalibration) {
4181 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 break;
4184 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 break;
4187 default:
4188 ALOG_ASSERT(false);
4189 }
4190
4191 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 mCalibration.distanceScale);
4194 }
4195
4196 switch (mCalibration.coverageCalibration) {
4197 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 break;
4200 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 break;
4203 default:
4204 ALOG_ASSERT(false);
4205 }
4206}
4207
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4209 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004210
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004211 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4212 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4213 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4214 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4215 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4216 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004217}
4218
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004219void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004220 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4221 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004222}
4223
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224void TouchInputMapper::reset(nsecs_t when) {
4225 mCursorButtonAccumulator.reset(getDevice());
4226 mCursorScrollAccumulator.reset(getDevice());
4227 mTouchButtonAccumulator.reset(getDevice());
4228
4229 mPointerVelocityControl.reset();
4230 mWheelXVelocityControl.reset();
4231 mWheelYVelocityControl.reset();
4232
Michael Wright842500e2015-03-13 17:32:02 -07004233 mRawStatesPending.clear();
4234 mCurrentRawState.clear();
4235 mCurrentCookedState.clear();
4236 mLastRawState.clear();
4237 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 mPointerUsage = POINTER_USAGE_NONE;
4239 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004240 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004241 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 mDownTime = 0;
4243
4244 mCurrentVirtualKey.down = false;
4245
4246 mPointerGesture.reset();
4247 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004248 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249
Yi Kong9b14ac62018-07-17 13:48:38 -07004250 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004251 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4252 mPointerController->clearSpots();
4253 }
4254
4255 InputMapper::reset(when);
4256}
4257
Michael Wright842500e2015-03-13 17:32:02 -07004258void TouchInputMapper::resetExternalStylus() {
4259 mExternalStylusState.clear();
4260 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004261 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004262 mExternalStylusDataPending = false;
4263}
4264
Michael Wright43fd19f2015-04-21 19:02:58 +01004265void TouchInputMapper::clearStylusDataPendingFlags() {
4266 mExternalStylusDataPending = false;
4267 mExternalStylusFusionTimeout = LLONG_MAX;
4268}
4269
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270void TouchInputMapper::process(const RawEvent* rawEvent) {
4271 mCursorButtonAccumulator.process(rawEvent);
4272 mCursorScrollAccumulator.process(rawEvent);
4273 mTouchButtonAccumulator.process(rawEvent);
4274
4275 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4276 sync(rawEvent->when);
4277 }
4278}
4279
4280void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004281 const RawState* last = mRawStatesPending.isEmpty() ?
4282 &mCurrentRawState : &mRawStatesPending.top();
4283
4284 // Push a new state.
4285 mRawStatesPending.push();
4286 RawState* next = &mRawStatesPending.editTop();
4287 next->clear();
4288 next->when = when;
4289
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004291 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 | mCursorButtonAccumulator.getButtonState();
4293
Michael Wright842500e2015-03-13 17:32:02 -07004294 // Sync scroll
4295 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4296 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 mCursorScrollAccumulator.finishSync();
4298
Michael Wright842500e2015-03-13 17:32:02 -07004299 // Sync touch
4300 syncTouch(when, next);
4301
4302 // Assign pointer ids.
4303 if (!mHavePointerIds) {
4304 assignPointerIds(last, next);
4305 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306
4307#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004308 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4309 "hovering ids 0x%08x -> 0x%08x",
4310 last->rawPointerData.pointerCount,
4311 next->rawPointerData.pointerCount,
4312 last->rawPointerData.touchingIdBits.value,
4313 next->rawPointerData.touchingIdBits.value,
4314 last->rawPointerData.hoveringIdBits.value,
4315 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316#endif
4317
Michael Wright842500e2015-03-13 17:32:02 -07004318 processRawTouches(false /*timeout*/);
4319}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004320
Michael Wright842500e2015-03-13 17:32:02 -07004321void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4323 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004324 mCurrentRawState.clear();
4325 mRawStatesPending.clear();
4326 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 }
4328
Michael Wright842500e2015-03-13 17:32:02 -07004329 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4330 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4331 // touching the current state will only observe the events that have been dispatched to the
4332 // rest of the pipeline.
4333 const size_t N = mRawStatesPending.size();
4334 size_t count;
4335 for(count = 0; count < N; count++) {
4336 const RawState& next = mRawStatesPending[count];
4337
4338 // A failure to assign the stylus id means that we're waiting on stylus data
4339 // and so should defer the rest of the pipeline.
4340 if (assignExternalStylusId(next, timeout)) {
4341 break;
4342 }
4343
4344 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004345 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004346 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004347 if (mCurrentRawState.when < mLastRawState.when) {
4348 mCurrentRawState.when = mLastRawState.when;
4349 }
Michael Wright842500e2015-03-13 17:32:02 -07004350 cookAndDispatch(mCurrentRawState.when);
4351 }
4352 if (count != 0) {
4353 mRawStatesPending.removeItemsAt(0, count);
4354 }
4355
Michael Wright842500e2015-03-13 17:32:02 -07004356 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004357 if (timeout) {
4358 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4359 clearStylusDataPendingFlags();
4360 mCurrentRawState.copyFrom(mLastRawState);
4361#if DEBUG_STYLUS_FUSION
4362 ALOGD("Timeout expired, synthesizing event with new stylus data");
4363#endif
4364 cookAndDispatch(when);
4365 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4366 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4367 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4368 }
Michael Wright842500e2015-03-13 17:32:02 -07004369 }
4370}
4371
4372void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4373 // Always start with a clean state.
4374 mCurrentCookedState.clear();
4375
4376 // Apply stylus buttons to current raw state.
4377 applyExternalStylusButtonState(when);
4378
4379 // Handle policy on initial down or hover events.
4380 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4381 && mCurrentRawState.rawPointerData.pointerCount != 0;
4382
4383 uint32_t policyFlags = 0;
4384 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4385 if (initialDown || buttonsPressed) {
4386 // If this is a touch screen, hide the pointer on an initial down.
4387 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4388 getContext()->fadePointer();
4389 }
4390
4391 if (mParameters.wake) {
4392 policyFlags |= POLICY_FLAG_WAKE;
4393 }
4394 }
4395
4396 // Consume raw off-screen touches before cooking pointer data.
4397 // If touches are consumed, subsequent code will not receive any pointer data.
4398 if (consumeRawTouches(when, policyFlags)) {
4399 mCurrentRawState.rawPointerData.clear();
4400 }
4401
4402 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4403 // with cooked pointer data that has the same ids and indices as the raw data.
4404 // The following code can use either the raw or cooked data, as needed.
4405 cookPointerData();
4406
4407 // Apply stylus pressure to current cooked state.
4408 applyExternalStylusTouchState(when);
4409
4410 // Synthesize key down from raw buttons if needed.
4411 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004412 mViewport.displayId, policyFlags,
4413 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004414
4415 // Dispatch the touches either directly or by translation through a pointer on screen.
4416 if (mDeviceMode == DEVICE_MODE_POINTER) {
4417 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4418 !idBits.isEmpty(); ) {
4419 uint32_t id = idBits.clearFirstMarkedBit();
4420 const RawPointerData::Pointer& pointer =
4421 mCurrentRawState.rawPointerData.pointerForId(id);
4422 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4423 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4424 mCurrentCookedState.stylusIdBits.markBit(id);
4425 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4426 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4427 mCurrentCookedState.fingerIdBits.markBit(id);
4428 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4429 mCurrentCookedState.mouseIdBits.markBit(id);
4430 }
4431 }
4432 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4433 !idBits.isEmpty(); ) {
4434 uint32_t id = idBits.clearFirstMarkedBit();
4435 const RawPointerData::Pointer& pointer =
4436 mCurrentRawState.rawPointerData.pointerForId(id);
4437 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4438 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4439 mCurrentCookedState.stylusIdBits.markBit(id);
4440 }
4441 }
4442
4443 // Stylus takes precedence over all tools, then mouse, then finger.
4444 PointerUsage pointerUsage = mPointerUsage;
4445 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4446 mCurrentCookedState.mouseIdBits.clear();
4447 mCurrentCookedState.fingerIdBits.clear();
4448 pointerUsage = POINTER_USAGE_STYLUS;
4449 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4450 mCurrentCookedState.fingerIdBits.clear();
4451 pointerUsage = POINTER_USAGE_MOUSE;
4452 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4453 isPointerDown(mCurrentRawState.buttonState)) {
4454 pointerUsage = POINTER_USAGE_GESTURES;
4455 }
4456
4457 dispatchPointerUsage(when, policyFlags, pointerUsage);
4458 } else {
4459 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004460 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004461 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4462 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4463
4464 mPointerController->setButtonState(mCurrentRawState.buttonState);
4465 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4466 mCurrentCookedState.cookedPointerData.idToIndex,
4467 mCurrentCookedState.cookedPointerData.touchingIdBits);
4468 }
4469
Michael Wright8e812822015-06-22 16:18:21 +01004470 if (!mCurrentMotionAborted) {
4471 dispatchButtonRelease(when, policyFlags);
4472 dispatchHoverExit(when, policyFlags);
4473 dispatchTouches(when, policyFlags);
4474 dispatchHoverEnterAndMove(when, policyFlags);
4475 dispatchButtonPress(when, policyFlags);
4476 }
4477
4478 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4479 mCurrentMotionAborted = false;
4480 }
Michael Wright842500e2015-03-13 17:32:02 -07004481 }
4482
4483 // Synthesize key up from raw buttons if needed.
4484 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004485 mViewport.displayId, policyFlags,
4486 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004487
4488 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004489 mCurrentRawState.rawVScroll = 0;
4490 mCurrentRawState.rawHScroll = 0;
4491
4492 // Copy current touch to last touch in preparation for the next cycle.
4493 mLastRawState.copyFrom(mCurrentRawState);
4494 mLastCookedState.copyFrom(mCurrentCookedState);
4495}
4496
4497void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004498 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004499 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4500 }
4501}
4502
4503void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004504 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4505 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004506
Michael Wright53dca3a2015-04-23 17:39:53 +01004507 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4508 float pressure = mExternalStylusState.pressure;
4509 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4510 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4511 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4512 }
4513 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4514 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4515
4516 PointerProperties& properties =
4517 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004518 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4519 properties.toolType = mExternalStylusState.toolType;
4520 }
4521 }
4522}
4523
4524bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4525 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4526 return false;
4527 }
4528
4529 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4530 && state.rawPointerData.pointerCount != 0;
4531 if (initialDown) {
4532 if (mExternalStylusState.pressure != 0.0f) {
4533#if DEBUG_STYLUS_FUSION
4534 ALOGD("Have both stylus and touch data, beginning fusion");
4535#endif
4536 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4537 } else if (timeout) {
4538#if DEBUG_STYLUS_FUSION
4539 ALOGD("Timeout expired, assuming touch is not a stylus.");
4540#endif
4541 resetExternalStylus();
4542 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004543 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4544 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004545 }
4546#if DEBUG_STYLUS_FUSION
4547 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004548 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004549#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004550 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004551 return true;
4552 }
4553 }
4554
4555 // Check if the stylus pointer has gone up.
4556 if (mExternalStylusId != -1 &&
4557 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4558#if DEBUG_STYLUS_FUSION
4559 ALOGD("Stylus pointer is going up");
4560#endif
4561 mExternalStylusId = -1;
4562 }
4563
4564 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004565}
4566
4567void TouchInputMapper::timeoutExpired(nsecs_t when) {
4568 if (mDeviceMode == DEVICE_MODE_POINTER) {
4569 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4570 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4571 }
Michael Wright842500e2015-03-13 17:32:02 -07004572 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004573 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004574 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004575 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4576 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004577 }
4578 }
4579}
4580
4581void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004582 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004583 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004584 // We're either in the middle of a fused stream of data or we're waiting on data before
4585 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4586 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004587 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004588 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004589 }
4590}
4591
4592bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4593 // Check for release of a virtual key.
4594 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004595 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 // Pointer went up while virtual key was down.
4597 mCurrentVirtualKey.down = false;
4598 if (!mCurrentVirtualKey.ignored) {
4599#if DEBUG_VIRTUAL_KEYS
4600 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4601 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4602#endif
4603 dispatchVirtualKey(when, policyFlags,
4604 AKEY_EVENT_ACTION_UP,
4605 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4606 }
4607 return true;
4608 }
4609
Michael Wright842500e2015-03-13 17:32:02 -07004610 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4611 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4612 const RawPointerData::Pointer& pointer =
4613 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4615 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4616 // Pointer is still within the space of the virtual key.
4617 return true;
4618 }
4619 }
4620
4621 // Pointer left virtual key area or another pointer also went down.
4622 // Send key cancellation but do not consume the touch yet.
4623 // This is useful when the user swipes through from the virtual key area
4624 // into the main display surface.
4625 mCurrentVirtualKey.down = false;
4626 if (!mCurrentVirtualKey.ignored) {
4627#if DEBUG_VIRTUAL_KEYS
4628 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4629 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4630#endif
4631 dispatchVirtualKey(when, policyFlags,
4632 AKEY_EVENT_ACTION_UP,
4633 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4634 | AKEY_EVENT_FLAG_CANCELED);
4635 }
4636 }
4637
Michael Wright842500e2015-03-13 17:32:02 -07004638 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4639 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004640 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004641 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4642 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4644 // If exactly one pointer went down, check for virtual key hit.
4645 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004646 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4648 if (virtualKey) {
4649 mCurrentVirtualKey.down = true;
4650 mCurrentVirtualKey.downTime = when;
4651 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4652 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4653 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4654 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4655
4656 if (!mCurrentVirtualKey.ignored) {
4657#if DEBUG_VIRTUAL_KEYS
4658 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4659 mCurrentVirtualKey.keyCode,
4660 mCurrentVirtualKey.scanCode);
4661#endif
4662 dispatchVirtualKey(when, policyFlags,
4663 AKEY_EVENT_ACTION_DOWN,
4664 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4665 }
4666 }
4667 }
4668 return true;
4669 }
4670 }
4671
4672 // Disable all virtual key touches that happen within a short time interval of the
4673 // most recent touch within the screen area. The idea is to filter out stray
4674 // virtual key presses when interacting with the touch screen.
4675 //
4676 // Problems we're trying to solve:
4677 //
4678 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4679 // virtual key area that is implemented by a separate touch panel and accidentally
4680 // triggers a virtual key.
4681 //
4682 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4683 // area and accidentally triggers a virtual key. This often happens when virtual keys
4684 // are layed out below the screen near to where the on screen keyboard's space bar
4685 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004686 if (mConfig.virtualKeyQuietTime > 0 &&
4687 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004688 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4689 }
4690 return false;
4691}
4692
4693void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4694 int32_t keyEventAction, int32_t keyEventFlags) {
4695 int32_t keyCode = mCurrentVirtualKey.keyCode;
4696 int32_t scanCode = mCurrentVirtualKey.scanCode;
4697 nsecs_t downTime = mCurrentVirtualKey.downTime;
4698 int32_t metaState = mContext->getGlobalMetaState();
4699 policyFlags |= POLICY_FLAG_VIRTUAL;
4700
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004701 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4702 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 getListener()->notifyKey(&args);
4704}
4705
Michael Wright8e812822015-06-22 16:18:21 +01004706void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4707 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4708 if (!currentIdBits.isEmpty()) {
4709 int32_t metaState = getContext()->getGlobalMetaState();
4710 int32_t buttonState = mCurrentCookedState.buttonState;
4711 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4712 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004713 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004714 mCurrentCookedState.cookedPointerData.pointerProperties,
4715 mCurrentCookedState.cookedPointerData.pointerCoords,
4716 mCurrentCookedState.cookedPointerData.idToIndex,
4717 currentIdBits, -1,
4718 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4719 mCurrentMotionAborted = true;
4720 }
4721}
4722
Michael Wrightd02c5b62014-02-10 15:10:22 -08004723void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004724 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4725 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004727 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004728
4729 if (currentIdBits == lastIdBits) {
4730 if (!currentIdBits.isEmpty()) {
4731 // No pointer id changes so this is a move event.
4732 // The listener takes care of batching moves so we don't have to deal with that here.
4733 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004734 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004735 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004736 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004737 mCurrentCookedState.cookedPointerData.pointerProperties,
4738 mCurrentCookedState.cookedPointerData.pointerCoords,
4739 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004740 currentIdBits, -1,
4741 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4742 }
4743 } else {
4744 // There may be pointers going up and pointers going down and pointers moving
4745 // all at the same time.
4746 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4747 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4748 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4749 BitSet32 dispatchedIdBits(lastIdBits.value);
4750
4751 // Update last coordinates of pointers that have moved so that we observe the new
4752 // pointer positions at the same time as other pointers that have just gone up.
4753 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004754 mCurrentCookedState.cookedPointerData.pointerProperties,
4755 mCurrentCookedState.cookedPointerData.pointerCoords,
4756 mCurrentCookedState.cookedPointerData.idToIndex,
4757 mLastCookedState.cookedPointerData.pointerProperties,
4758 mLastCookedState.cookedPointerData.pointerCoords,
4759 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004761 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762 moveNeeded = true;
4763 }
4764
4765 // Dispatch pointer up events.
4766 while (!upIdBits.isEmpty()) {
4767 uint32_t upId = upIdBits.clearFirstMarkedBit();
4768
4769 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004770 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004771 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004772 mLastCookedState.cookedPointerData.pointerProperties,
4773 mLastCookedState.cookedPointerData.pointerCoords,
4774 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004775 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 dispatchedIdBits.clearBit(upId);
4777 }
4778
4779 // Dispatch move events if any of the remaining pointers moved from their old locations.
4780 // Although applications receive new locations as part of individual pointer up
4781 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004782 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4784 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004785 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004786 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004787 mCurrentCookedState.cookedPointerData.pointerProperties,
4788 mCurrentCookedState.cookedPointerData.pointerCoords,
4789 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004790 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 }
4792
4793 // Dispatch pointer down events using the new pointer locations.
4794 while (!downIdBits.isEmpty()) {
4795 uint32_t downId = downIdBits.clearFirstMarkedBit();
4796 dispatchedIdBits.markBit(downId);
4797
4798 if (dispatchedIdBits.count() == 1) {
4799 // First pointer is going down. Set down time.
4800 mDownTime = when;
4801 }
4802
4803 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004804 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004805 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004806 mCurrentCookedState.cookedPointerData.pointerProperties,
4807 mCurrentCookedState.cookedPointerData.pointerCoords,
4808 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004809 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 }
4811 }
4812}
4813
4814void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4815 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004816 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4817 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 int32_t metaState = getContext()->getGlobalMetaState();
4819 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004820 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004821 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004822 mLastCookedState.cookedPointerData.pointerProperties,
4823 mLastCookedState.cookedPointerData.pointerCoords,
4824 mLastCookedState.cookedPointerData.idToIndex,
4825 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4827 mSentHoverEnter = false;
4828 }
4829}
4830
4831void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004832 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4833 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 int32_t metaState = getContext()->getGlobalMetaState();
4835 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004836 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004837 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004838 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004839 mCurrentCookedState.cookedPointerData.pointerProperties,
4840 mCurrentCookedState.cookedPointerData.pointerCoords,
4841 mCurrentCookedState.cookedPointerData.idToIndex,
4842 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4844 mSentHoverEnter = true;
4845 }
4846
4847 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004848 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004849 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004850 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004851 mCurrentCookedState.cookedPointerData.pointerProperties,
4852 mCurrentCookedState.cookedPointerData.pointerCoords,
4853 mCurrentCookedState.cookedPointerData.idToIndex,
4854 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4856 }
4857}
4858
Michael Wright7b159c92015-05-14 14:48:03 +01004859void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4860 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4861 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4862 const int32_t metaState = getContext()->getGlobalMetaState();
4863 int32_t buttonState = mLastCookedState.buttonState;
4864 while (!releasedButtons.isEmpty()) {
4865 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4866 buttonState &= ~actionButton;
4867 dispatchMotion(when, policyFlags, mSource,
4868 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4869 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004870 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004871 mCurrentCookedState.cookedPointerData.pointerProperties,
4872 mCurrentCookedState.cookedPointerData.pointerCoords,
4873 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4874 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4875 }
4876}
4877
4878void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4879 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4880 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4881 const int32_t metaState = getContext()->getGlobalMetaState();
4882 int32_t buttonState = mLastCookedState.buttonState;
4883 while (!pressedButtons.isEmpty()) {
4884 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4885 buttonState |= actionButton;
4886 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4887 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004888 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004889 mCurrentCookedState.cookedPointerData.pointerProperties,
4890 mCurrentCookedState.cookedPointerData.pointerCoords,
4891 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4892 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4893 }
4894}
4895
4896const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4897 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4898 return cookedPointerData.touchingIdBits;
4899 }
4900 return cookedPointerData.hoveringIdBits;
4901}
4902
Michael Wrightd02c5b62014-02-10 15:10:22 -08004903void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004904 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905
Michael Wright842500e2015-03-13 17:32:02 -07004906 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004907 mCurrentCookedState.deviceTimestamp =
4908 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004909 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4910 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4911 mCurrentRawState.rawPointerData.hoveringIdBits;
4912 mCurrentCookedState.cookedPointerData.touchingIdBits =
4913 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914
Michael Wright7b159c92015-05-14 14:48:03 +01004915 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4916 mCurrentCookedState.buttonState = 0;
4917 } else {
4918 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4919 }
4920
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 // Walk through the the active pointers and map device coordinates onto
4922 // surface coordinates and adjust for display orientation.
4923 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004924 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004925
4926 // Size
4927 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4928 switch (mCalibration.sizeCalibration) {
4929 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4930 case Calibration::SIZE_CALIBRATION_DIAMETER:
4931 case Calibration::SIZE_CALIBRATION_BOX:
4932 case Calibration::SIZE_CALIBRATION_AREA:
4933 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4934 touchMajor = in.touchMajor;
4935 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4936 toolMajor = in.toolMajor;
4937 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4938 size = mRawPointerAxes.touchMinor.valid
4939 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4940 } else if (mRawPointerAxes.touchMajor.valid) {
4941 toolMajor = touchMajor = in.touchMajor;
4942 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4943 ? in.touchMinor : in.touchMajor;
4944 size = mRawPointerAxes.touchMinor.valid
4945 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4946 } else if (mRawPointerAxes.toolMajor.valid) {
4947 touchMajor = toolMajor = in.toolMajor;
4948 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4949 ? in.toolMinor : in.toolMajor;
4950 size = mRawPointerAxes.toolMinor.valid
4951 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4952 } else {
4953 ALOG_ASSERT(false, "No touch or tool axes. "
4954 "Size calibration should have been resolved to NONE.");
4955 touchMajor = 0;
4956 touchMinor = 0;
4957 toolMajor = 0;
4958 toolMinor = 0;
4959 size = 0;
4960 }
4961
4962 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004963 uint32_t touchingCount =
4964 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965 if (touchingCount > 1) {
4966 touchMajor /= touchingCount;
4967 touchMinor /= touchingCount;
4968 toolMajor /= touchingCount;
4969 toolMinor /= touchingCount;
4970 size /= touchingCount;
4971 }
4972 }
4973
4974 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4975 touchMajor *= mGeometricScale;
4976 touchMinor *= mGeometricScale;
4977 toolMajor *= mGeometricScale;
4978 toolMinor *= mGeometricScale;
4979 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4980 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4981 touchMinor = touchMajor;
4982 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4983 toolMinor = toolMajor;
4984 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4985 touchMinor = touchMajor;
4986 toolMinor = toolMajor;
4987 }
4988
4989 mCalibration.applySizeScaleAndBias(&touchMajor);
4990 mCalibration.applySizeScaleAndBias(&touchMinor);
4991 mCalibration.applySizeScaleAndBias(&toolMajor);
4992 mCalibration.applySizeScaleAndBias(&toolMinor);
4993 size *= mSizeScale;
4994 break;
4995 default:
4996 touchMajor = 0;
4997 touchMinor = 0;
4998 toolMajor = 0;
4999 toolMinor = 0;
5000 size = 0;
5001 break;
5002 }
5003
5004 // Pressure
5005 float pressure;
5006 switch (mCalibration.pressureCalibration) {
5007 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5008 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5009 pressure = in.pressure * mPressureScale;
5010 break;
5011 default:
5012 pressure = in.isHovering ? 0 : 1;
5013 break;
5014 }
5015
5016 // Tilt and Orientation
5017 float tilt;
5018 float orientation;
5019 if (mHaveTilt) {
5020 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5021 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5022 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5023 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5024 } else {
5025 tilt = 0;
5026
5027 switch (mCalibration.orientationCalibration) {
5028 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5029 orientation = in.orientation * mOrientationScale;
5030 break;
5031 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5032 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5033 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5034 if (c1 != 0 || c2 != 0) {
5035 orientation = atan2f(c1, c2) * 0.5f;
5036 float confidence = hypotf(c1, c2);
5037 float scale = 1.0f + confidence / 16.0f;
5038 touchMajor *= scale;
5039 touchMinor /= scale;
5040 toolMajor *= scale;
5041 toolMinor /= scale;
5042 } else {
5043 orientation = 0;
5044 }
5045 break;
5046 }
5047 default:
5048 orientation = 0;
5049 }
5050 }
5051
5052 // Distance
5053 float distance;
5054 switch (mCalibration.distanceCalibration) {
5055 case Calibration::DISTANCE_CALIBRATION_SCALED:
5056 distance = in.distance * mDistanceScale;
5057 break;
5058 default:
5059 distance = 0;
5060 }
5061
5062 // Coverage
5063 int32_t rawLeft, rawTop, rawRight, rawBottom;
5064 switch (mCalibration.coverageCalibration) {
5065 case Calibration::COVERAGE_CALIBRATION_BOX:
5066 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5067 rawRight = in.toolMinor & 0x0000ffff;
5068 rawBottom = in.toolMajor & 0x0000ffff;
5069 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5070 break;
5071 default:
5072 rawLeft = rawTop = rawRight = rawBottom = 0;
5073 break;
5074 }
5075
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005076 // Adjust X,Y coords for device calibration
5077 // TODO: Adjust coverage coords?
5078 float xTransformed = in.x, yTransformed = in.y;
5079 mAffineTransform.applyTo(xTransformed, yTransformed);
5080
5081 // Adjust X, Y, and coverage coords for surface orientation.
5082 float x, y;
5083 float left, top, right, bottom;
5084
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085 switch (mSurfaceOrientation) {
5086 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005087 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5088 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005089 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5090 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5091 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5092 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5093 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005094 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005095 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5096 }
5097 break;
5098 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005099 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005100 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005101 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5102 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5104 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5105 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005106 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5108 }
5109 break;
5110 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005111 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005112 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005113 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5114 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5116 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5117 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005118 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005119 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5120 }
5121 break;
5122 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005123 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5124 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005125 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5126 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5127 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5128 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5129 break;
5130 }
5131
5132 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005133 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 out.clear();
5135 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5136 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5137 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5138 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5139 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5140 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5141 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5142 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5144 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5145 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5146 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5149 } else {
5150 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5151 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5152 }
5153
5154 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005155 PointerProperties& properties =
5156 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 uint32_t id = in.id;
5158 properties.clear();
5159 properties.id = id;
5160 properties.toolType = in.toolType;
5161
5162 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005163 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 }
5165}
5166
5167void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5168 PointerUsage pointerUsage) {
5169 if (pointerUsage != mPointerUsage) {
5170 abortPointerUsage(when, policyFlags);
5171 mPointerUsage = pointerUsage;
5172 }
5173
5174 switch (mPointerUsage) {
5175 case POINTER_USAGE_GESTURES:
5176 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5177 break;
5178 case POINTER_USAGE_STYLUS:
5179 dispatchPointerStylus(when, policyFlags);
5180 break;
5181 case POINTER_USAGE_MOUSE:
5182 dispatchPointerMouse(when, policyFlags);
5183 break;
5184 default:
5185 break;
5186 }
5187}
5188
5189void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5190 switch (mPointerUsage) {
5191 case POINTER_USAGE_GESTURES:
5192 abortPointerGestures(when, policyFlags);
5193 break;
5194 case POINTER_USAGE_STYLUS:
5195 abortPointerStylus(when, policyFlags);
5196 break;
5197 case POINTER_USAGE_MOUSE:
5198 abortPointerMouse(when, policyFlags);
5199 break;
5200 default:
5201 break;
5202 }
5203
5204 mPointerUsage = POINTER_USAGE_NONE;
5205}
5206
5207void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5208 bool isTimeout) {
5209 // Update current gesture coordinates.
5210 bool cancelPreviousGesture, finishPreviousGesture;
5211 bool sendEvents = preparePointerGestures(when,
5212 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5213 if (!sendEvents) {
5214 return;
5215 }
5216 if (finishPreviousGesture) {
5217 cancelPreviousGesture = false;
5218 }
5219
5220 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005221 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5222 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005223 if (finishPreviousGesture || cancelPreviousGesture) {
5224 mPointerController->clearSpots();
5225 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005226
5227 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5228 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5229 mPointerGesture.currentGestureIdToIndex,
5230 mPointerGesture.currentGestureIdBits);
5231 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005232 } else {
5233 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5234 }
5235
5236 // Show or hide the pointer if needed.
5237 switch (mPointerGesture.currentGestureMode) {
5238 case PointerGesture::NEUTRAL:
5239 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005240 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5241 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005242 // Remind the user of where the pointer is after finishing a gesture with spots.
5243 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5244 }
5245 break;
5246 case PointerGesture::TAP:
5247 case PointerGesture::TAP_DRAG:
5248 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5249 case PointerGesture::HOVER:
5250 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005251 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 // Unfade the pointer when the current gesture manipulates the
5253 // area directly under the pointer.
5254 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5255 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 case PointerGesture::FREEFORM:
5257 // Fade the pointer when the current gesture manipulates a different
5258 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005259 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5261 } else {
5262 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5263 }
5264 break;
5265 }
5266
5267 // Send events!
5268 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005269 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005270
5271 // Update last coordinates of pointers that have moved so that we observe the new
5272 // pointer positions at the same time as other pointers that have just gone up.
5273 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5274 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5275 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5276 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5277 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5278 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5279 bool moveNeeded = false;
5280 if (down && !cancelPreviousGesture && !finishPreviousGesture
5281 && !mPointerGesture.lastGestureIdBits.isEmpty()
5282 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5283 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5284 & mPointerGesture.lastGestureIdBits.value);
5285 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5286 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5287 mPointerGesture.lastGestureProperties,
5288 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5289 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005290 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 moveNeeded = true;
5292 }
5293 }
5294
5295 // Send motion events for all pointers that went up or were canceled.
5296 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5297 if (!dispatchedGestureIdBits.isEmpty()) {
5298 if (cancelPreviousGesture) {
5299 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005300 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005301 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 mPointerGesture.lastGestureProperties,
5303 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005304 dispatchedGestureIdBits, -1, 0,
5305 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005306
5307 dispatchedGestureIdBits.clear();
5308 } else {
5309 BitSet32 upGestureIdBits;
5310 if (finishPreviousGesture) {
5311 upGestureIdBits = dispatchedGestureIdBits;
5312 } else {
5313 upGestureIdBits.value = dispatchedGestureIdBits.value
5314 & ~mPointerGesture.currentGestureIdBits.value;
5315 }
5316 while (!upGestureIdBits.isEmpty()) {
5317 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5318
5319 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005320 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005322 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 mPointerGesture.lastGestureProperties,
5324 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5325 dispatchedGestureIdBits, id,
5326 0, 0, mPointerGesture.downTime);
5327
5328 dispatchedGestureIdBits.clearBit(id);
5329 }
5330 }
5331 }
5332
5333 // Send motion events for all pointers that moved.
5334 if (moveNeeded) {
5335 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005336 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005337 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005338 mPointerGesture.currentGestureProperties,
5339 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5340 dispatchedGestureIdBits, -1,
5341 0, 0, mPointerGesture.downTime);
5342 }
5343
5344 // Send motion events for all pointers that went down.
5345 if (down) {
5346 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5347 & ~dispatchedGestureIdBits.value);
5348 while (!downGestureIdBits.isEmpty()) {
5349 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5350 dispatchedGestureIdBits.markBit(id);
5351
5352 if (dispatchedGestureIdBits.count() == 1) {
5353 mPointerGesture.downTime = when;
5354 }
5355
5356 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005357 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005358 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 mPointerGesture.currentGestureProperties,
5360 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5361 dispatchedGestureIdBits, id,
5362 0, 0, mPointerGesture.downTime);
5363 }
5364 }
5365
5366 // Send motion events for hover.
5367 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5368 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005369 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005370 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 mPointerGesture.currentGestureProperties,
5372 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5373 mPointerGesture.currentGestureIdBits, -1,
5374 0, 0, mPointerGesture.downTime);
5375 } else if (dispatchedGestureIdBits.isEmpty()
5376 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5377 // Synthesize a hover move event after all pointers go up to indicate that
5378 // the pointer is hovering again even if the user is not currently touching
5379 // the touch pad. This ensures that a view will receive a fresh hover enter
5380 // event after a tap.
5381 float x, y;
5382 mPointerController->getPosition(&x, &y);
5383
5384 PointerProperties pointerProperties;
5385 pointerProperties.clear();
5386 pointerProperties.id = 0;
5387 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5388
5389 PointerCoords pointerCoords;
5390 pointerCoords.clear();
5391 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5392 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5393
Andrii Kulian620f6d92018-09-14 16:51:59 -07005394 int32_t displayId = mPointerController->getDisplayId();
5395 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005396 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005397 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005398 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 0, 0, mPointerGesture.downTime);
5400 getListener()->notifyMotion(&args);
5401 }
5402
5403 // Update state.
5404 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5405 if (!down) {
5406 mPointerGesture.lastGestureIdBits.clear();
5407 } else {
5408 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5409 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5410 uint32_t id = idBits.clearFirstMarkedBit();
5411 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5412 mPointerGesture.lastGestureProperties[index].copyFrom(
5413 mPointerGesture.currentGestureProperties[index]);
5414 mPointerGesture.lastGestureCoords[index].copyFrom(
5415 mPointerGesture.currentGestureCoords[index]);
5416 mPointerGesture.lastGestureIdToIndex[id] = index;
5417 }
5418 }
5419}
5420
5421void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5422 // Cancel previously dispatches pointers.
5423 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5424 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005425 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005427 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005428 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 mPointerGesture.lastGestureProperties,
5430 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5431 mPointerGesture.lastGestureIdBits, -1,
5432 0, 0, mPointerGesture.downTime);
5433 }
5434
5435 // Reset the current pointer gesture.
5436 mPointerGesture.reset();
5437 mPointerVelocityControl.reset();
5438
5439 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005440 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5442 mPointerController->clearSpots();
5443 }
5444}
5445
5446bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5447 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5448 *outCancelPreviousGesture = false;
5449 *outFinishPreviousGesture = false;
5450
5451 // Handle TAP timeout.
5452 if (isTimeout) {
5453#if DEBUG_GESTURES
5454 ALOGD("Gestures: Processing timeout");
5455#endif
5456
5457 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5458 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5459 // The tap/drag timeout has not yet expired.
5460 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5461 + mConfig.pointerGestureTapDragInterval);
5462 } else {
5463 // The tap is finished.
5464#if DEBUG_GESTURES
5465 ALOGD("Gestures: TAP finished");
5466#endif
5467 *outFinishPreviousGesture = true;
5468
5469 mPointerGesture.activeGestureId = -1;
5470 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5471 mPointerGesture.currentGestureIdBits.clear();
5472
5473 mPointerVelocityControl.reset();
5474 return true;
5475 }
5476 }
5477
5478 // We did not handle this timeout.
5479 return false;
5480 }
5481
Michael Wright842500e2015-03-13 17:32:02 -07005482 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5483 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484
5485 // Update the velocity tracker.
5486 {
5487 VelocityTracker::Position positions[MAX_POINTERS];
5488 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005489 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005491 const RawPointerData::Pointer& pointer =
5492 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 positions[count].x = pointer.x * mPointerXMovementScale;
5494 positions[count].y = pointer.y * mPointerYMovementScale;
5495 }
5496 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005497 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 }
5499
5500 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5501 // to NEUTRAL, then we should not generate tap event.
5502 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5503 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5504 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5505 mPointerGesture.resetTap();
5506 }
5507
5508 // Pick a new active touch id if needed.
5509 // Choose an arbitrary pointer that just went down, if there is one.
5510 // Otherwise choose an arbitrary remaining pointer.
5511 // This guarantees we always have an active touch id when there is at least one pointer.
5512 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005513 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5514 int32_t activeTouchId = lastActiveTouchId;
5515 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005516 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005518 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 mPointerGesture.firstTouchTime = when;
5520 }
Michael Wright842500e2015-03-13 17:32:02 -07005521 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005522 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005523 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005524 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 } else {
5526 activeTouchId = mPointerGesture.activeTouchId = -1;
5527 }
5528 }
5529
5530 // Determine whether we are in quiet time.
5531 bool isQuietTime = false;
5532 if (activeTouchId < 0) {
5533 mPointerGesture.resetQuietTime();
5534 } else {
5535 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5536 if (!isQuietTime) {
5537 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5538 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5539 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5540 && currentFingerCount < 2) {
5541 // Enter quiet time when exiting swipe or freeform state.
5542 // This is to prevent accidentally entering the hover state and flinging the
5543 // pointer when finishing a swipe and there is still one pointer left onscreen.
5544 isQuietTime = true;
5545 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5546 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005547 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 // Enter quiet time when releasing the button and there are still two or more
5549 // fingers down. This may indicate that one finger was used to press the button
5550 // but it has not gone up yet.
5551 isQuietTime = true;
5552 }
5553 if (isQuietTime) {
5554 mPointerGesture.quietTime = when;
5555 }
5556 }
5557 }
5558
5559 // Switch states based on button and pointer state.
5560 if (isQuietTime) {
5561 // Case 1: Quiet time. (QUIET)
5562#if DEBUG_GESTURES
5563 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5564 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5565#endif
5566 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5567 *outFinishPreviousGesture = true;
5568 }
5569
5570 mPointerGesture.activeGestureId = -1;
5571 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5572 mPointerGesture.currentGestureIdBits.clear();
5573
5574 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005575 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5577 // The pointer follows the active touch point.
5578 // Emit DOWN, MOVE, UP events at the pointer location.
5579 //
5580 // Only the active touch matters; other fingers are ignored. This policy helps
5581 // to handle the case where the user places a second finger on the touch pad
5582 // to apply the necessary force to depress an integrated button below the surface.
5583 // We don't want the second finger to be delivered to applications.
5584 //
5585 // For this to work well, we need to make sure to track the pointer that is really
5586 // active. If the user first puts one finger down to click then adds another
5587 // finger to drag then the active pointer should switch to the finger that is
5588 // being dragged.
5589#if DEBUG_GESTURES
5590 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5591 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5592#endif
5593 // Reset state when just starting.
5594 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5595 *outFinishPreviousGesture = true;
5596 mPointerGesture.activeGestureId = 0;
5597 }
5598
5599 // Switch pointers if needed.
5600 // Find the fastest pointer and follow it.
5601 if (activeTouchId >= 0 && currentFingerCount > 1) {
5602 int32_t bestId = -1;
5603 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005604 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 uint32_t id = idBits.clearFirstMarkedBit();
5606 float vx, vy;
5607 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5608 float speed = hypotf(vx, vy);
5609 if (speed > bestSpeed) {
5610 bestId = id;
5611 bestSpeed = speed;
5612 }
5613 }
5614 }
5615 if (bestId >= 0 && bestId != activeTouchId) {
5616 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617#if DEBUG_GESTURES
5618 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5619 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5620#endif
5621 }
5622 }
5623
Jun Mukaifa1706a2015-12-03 01:14:46 -08005624 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005625 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005626 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005627 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005629 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005630 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5631 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005632
5633 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5634 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5635
5636 // Move the pointer using a relative motion.
5637 // When using spots, the click will occur at the position of the anchor
5638 // spot and all other spots will move there.
5639 mPointerController->move(deltaX, deltaY);
5640 } else {
5641 mPointerVelocityControl.reset();
5642 }
5643
5644 float x, y;
5645 mPointerController->getPosition(&x, &y);
5646
5647 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5648 mPointerGesture.currentGestureIdBits.clear();
5649 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5650 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5651 mPointerGesture.currentGestureProperties[0].clear();
5652 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5653 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5654 mPointerGesture.currentGestureCoords[0].clear();
5655 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5656 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5657 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5658 } else if (currentFingerCount == 0) {
5659 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5660 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5661 *outFinishPreviousGesture = true;
5662 }
5663
5664 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5665 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5666 bool tapped = false;
5667 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5668 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5669 && lastFingerCount == 1) {
5670 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5671 float x, y;
5672 mPointerController->getPosition(&x, &y);
5673 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5674 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5675#if DEBUG_GESTURES
5676 ALOGD("Gestures: TAP");
5677#endif
5678
5679 mPointerGesture.tapUpTime = when;
5680 getContext()->requestTimeoutAtTime(when
5681 + mConfig.pointerGestureTapDragInterval);
5682
5683 mPointerGesture.activeGestureId = 0;
5684 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5685 mPointerGesture.currentGestureIdBits.clear();
5686 mPointerGesture.currentGestureIdBits.markBit(
5687 mPointerGesture.activeGestureId);
5688 mPointerGesture.currentGestureIdToIndex[
5689 mPointerGesture.activeGestureId] = 0;
5690 mPointerGesture.currentGestureProperties[0].clear();
5691 mPointerGesture.currentGestureProperties[0].id =
5692 mPointerGesture.activeGestureId;
5693 mPointerGesture.currentGestureProperties[0].toolType =
5694 AMOTION_EVENT_TOOL_TYPE_FINGER;
5695 mPointerGesture.currentGestureCoords[0].clear();
5696 mPointerGesture.currentGestureCoords[0].setAxisValue(
5697 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5698 mPointerGesture.currentGestureCoords[0].setAxisValue(
5699 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5700 mPointerGesture.currentGestureCoords[0].setAxisValue(
5701 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5702
5703 tapped = true;
5704 } else {
5705#if DEBUG_GESTURES
5706 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5707 x - mPointerGesture.tapX,
5708 y - mPointerGesture.tapY);
5709#endif
5710 }
5711 } else {
5712#if DEBUG_GESTURES
5713 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5714 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5715 (when - mPointerGesture.tapDownTime) * 0.000001f);
5716 } else {
5717 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5718 }
5719#endif
5720 }
5721 }
5722
5723 mPointerVelocityControl.reset();
5724
5725 if (!tapped) {
5726#if DEBUG_GESTURES
5727 ALOGD("Gestures: NEUTRAL");
5728#endif
5729 mPointerGesture.activeGestureId = -1;
5730 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5731 mPointerGesture.currentGestureIdBits.clear();
5732 }
5733 } else if (currentFingerCount == 1) {
5734 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5735 // The pointer follows the active touch point.
5736 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5737 // When in TAP_DRAG, emit MOVE events at the pointer location.
5738 ALOG_ASSERT(activeTouchId >= 0);
5739
5740 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5741 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5742 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5743 float x, y;
5744 mPointerController->getPosition(&x, &y);
5745 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5746 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5747 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5748 } else {
5749#if DEBUG_GESTURES
5750 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5751 x - mPointerGesture.tapX,
5752 y - mPointerGesture.tapY);
5753#endif
5754 }
5755 } else {
5756#if DEBUG_GESTURES
5757 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5758 (when - mPointerGesture.tapUpTime) * 0.000001f);
5759#endif
5760 }
5761 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5762 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5763 }
5764
Jun Mukaifa1706a2015-12-03 01:14:46 -08005765 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005766 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005767 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005768 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005769 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005770 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005771 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5772 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773
5774 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5775 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5776
5777 // Move the pointer using a relative motion.
5778 // When using spots, the hover or drag will occur at the position of the anchor spot.
5779 mPointerController->move(deltaX, deltaY);
5780 } else {
5781 mPointerVelocityControl.reset();
5782 }
5783
5784 bool down;
5785 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5786#if DEBUG_GESTURES
5787 ALOGD("Gestures: TAP_DRAG");
5788#endif
5789 down = true;
5790 } else {
5791#if DEBUG_GESTURES
5792 ALOGD("Gestures: HOVER");
5793#endif
5794 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5795 *outFinishPreviousGesture = true;
5796 }
5797 mPointerGesture.activeGestureId = 0;
5798 down = false;
5799 }
5800
5801 float x, y;
5802 mPointerController->getPosition(&x, &y);
5803
5804 mPointerGesture.currentGestureIdBits.clear();
5805 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5806 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5807 mPointerGesture.currentGestureProperties[0].clear();
5808 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5809 mPointerGesture.currentGestureProperties[0].toolType =
5810 AMOTION_EVENT_TOOL_TYPE_FINGER;
5811 mPointerGesture.currentGestureCoords[0].clear();
5812 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5813 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5814 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5815 down ? 1.0f : 0.0f);
5816
5817 if (lastFingerCount == 0 && currentFingerCount != 0) {
5818 mPointerGesture.resetTap();
5819 mPointerGesture.tapDownTime = when;
5820 mPointerGesture.tapX = x;
5821 mPointerGesture.tapY = y;
5822 }
5823 } else {
5824 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5825 // We need to provide feedback for each finger that goes down so we cannot wait
5826 // for the fingers to move before deciding what to do.
5827 //
5828 // The ambiguous case is deciding what to do when there are two fingers down but they
5829 // have not moved enough to determine whether they are part of a drag or part of a
5830 // freeform gesture, or just a press or long-press at the pointer location.
5831 //
5832 // When there are two fingers we start with the PRESS hypothesis and we generate a
5833 // down at the pointer location.
5834 //
5835 // When the two fingers move enough or when additional fingers are added, we make
5836 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5837 ALOG_ASSERT(activeTouchId >= 0);
5838
5839 bool settled = when >= mPointerGesture.firstTouchTime
5840 + mConfig.pointerGestureMultitouchSettleInterval;
5841 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5842 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5843 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5844 *outFinishPreviousGesture = true;
5845 } else if (!settled && currentFingerCount > lastFingerCount) {
5846 // Additional pointers have gone down but not yet settled.
5847 // Reset the gesture.
5848#if DEBUG_GESTURES
5849 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5850 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5851 + mConfig.pointerGestureMultitouchSettleInterval - when)
5852 * 0.000001f);
5853#endif
5854 *outCancelPreviousGesture = true;
5855 } else {
5856 // Continue previous gesture.
5857 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5858 }
5859
5860 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5861 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5862 mPointerGesture.activeGestureId = 0;
5863 mPointerGesture.referenceIdBits.clear();
5864 mPointerVelocityControl.reset();
5865
5866 // Use the centroid and pointer location as the reference points for the gesture.
5867#if DEBUG_GESTURES
5868 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5869 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5870 + mConfig.pointerGestureMultitouchSettleInterval - when)
5871 * 0.000001f);
5872#endif
Michael Wright842500e2015-03-13 17:32:02 -07005873 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005874 &mPointerGesture.referenceTouchX,
5875 &mPointerGesture.referenceTouchY);
5876 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5877 &mPointerGesture.referenceGestureY);
5878 }
5879
5880 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005881 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5883 uint32_t id = idBits.clearFirstMarkedBit();
5884 mPointerGesture.referenceDeltas[id].dx = 0;
5885 mPointerGesture.referenceDeltas[id].dy = 0;
5886 }
Michael Wright842500e2015-03-13 17:32:02 -07005887 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888
5889 // Add delta for all fingers and calculate a common movement delta.
5890 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005891 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5892 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5894 bool first = (idBits == commonIdBits);
5895 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005896 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5897 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5899 delta.dx += cpd.x - lpd.x;
5900 delta.dy += cpd.y - lpd.y;
5901
5902 if (first) {
5903 commonDeltaX = delta.dx;
5904 commonDeltaY = delta.dy;
5905 } else {
5906 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5907 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5908 }
5909 }
5910
5911 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5912 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5913 float dist[MAX_POINTER_ID + 1];
5914 int32_t distOverThreshold = 0;
5915 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5916 uint32_t id = idBits.clearFirstMarkedBit();
5917 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5918 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5919 delta.dy * mPointerYZoomScale);
5920 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5921 distOverThreshold += 1;
5922 }
5923 }
5924
5925 // Only transition when at least two pointers have moved further than
5926 // the minimum distance threshold.
5927 if (distOverThreshold >= 2) {
5928 if (currentFingerCount > 2) {
5929 // There are more than two pointers, switch to FREEFORM.
5930#if DEBUG_GESTURES
5931 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5932 currentFingerCount);
5933#endif
5934 *outCancelPreviousGesture = true;
5935 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5936 } else {
5937 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005938 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 uint32_t id1 = idBits.clearFirstMarkedBit();
5940 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005941 const RawPointerData::Pointer& p1 =
5942 mCurrentRawState.rawPointerData.pointerForId(id1);
5943 const RawPointerData::Pointer& p2 =
5944 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005945 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5946 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5947 // There are two pointers but they are too far apart for a SWIPE,
5948 // switch to FREEFORM.
5949#if DEBUG_GESTURES
5950 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5951 mutualDistance, mPointerGestureMaxSwipeWidth);
5952#endif
5953 *outCancelPreviousGesture = true;
5954 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5955 } else {
5956 // There are two pointers. Wait for both pointers to start moving
5957 // before deciding whether this is a SWIPE or FREEFORM gesture.
5958 float dist1 = dist[id1];
5959 float dist2 = dist[id2];
5960 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5961 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5962 // Calculate the dot product of the displacement vectors.
5963 // When the vectors are oriented in approximately the same direction,
5964 // the angle betweeen them is near zero and the cosine of the angle
5965 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5966 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5967 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5968 float dx1 = delta1.dx * mPointerXZoomScale;
5969 float dy1 = delta1.dy * mPointerYZoomScale;
5970 float dx2 = delta2.dx * mPointerXZoomScale;
5971 float dy2 = delta2.dy * mPointerYZoomScale;
5972 float dot = dx1 * dx2 + dy1 * dy2;
5973 float cosine = dot / (dist1 * dist2); // denominator always > 0
5974 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5975 // Pointers are moving in the same direction. Switch to SWIPE.
5976#if DEBUG_GESTURES
5977 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5978 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5979 "cosine %0.3f >= %0.3f",
5980 dist1, mConfig.pointerGestureMultitouchMinDistance,
5981 dist2, mConfig.pointerGestureMultitouchMinDistance,
5982 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5983#endif
5984 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5985 } else {
5986 // Pointers are moving in different directions. Switch to FREEFORM.
5987#if DEBUG_GESTURES
5988 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5989 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5990 "cosine %0.3f < %0.3f",
5991 dist1, mConfig.pointerGestureMultitouchMinDistance,
5992 dist2, mConfig.pointerGestureMultitouchMinDistance,
5993 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5994#endif
5995 *outCancelPreviousGesture = true;
5996 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5997 }
5998 }
5999 }
6000 }
6001 }
6002 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6003 // Switch from SWIPE to FREEFORM if additional pointers go down.
6004 // Cancel previous gesture.
6005 if (currentFingerCount > 2) {
6006#if DEBUG_GESTURES
6007 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6008 currentFingerCount);
6009#endif
6010 *outCancelPreviousGesture = true;
6011 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6012 }
6013 }
6014
6015 // Move the reference points based on the overall group motion of the fingers
6016 // except in PRESS mode while waiting for a transition to occur.
6017 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6018 && (commonDeltaX || commonDeltaY)) {
6019 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6020 uint32_t id = idBits.clearFirstMarkedBit();
6021 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6022 delta.dx = 0;
6023 delta.dy = 0;
6024 }
6025
6026 mPointerGesture.referenceTouchX += commonDeltaX;
6027 mPointerGesture.referenceTouchY += commonDeltaY;
6028
6029 commonDeltaX *= mPointerXMovementScale;
6030 commonDeltaY *= mPointerYMovementScale;
6031
6032 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6033 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6034
6035 mPointerGesture.referenceGestureX += commonDeltaX;
6036 mPointerGesture.referenceGestureY += commonDeltaY;
6037 }
6038
6039 // Report gestures.
6040 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6041 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6042 // PRESS or SWIPE mode.
6043#if DEBUG_GESTURES
6044 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6045 "activeGestureId=%d, currentTouchPointerCount=%d",
6046 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6047#endif
6048 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6049
6050 mPointerGesture.currentGestureIdBits.clear();
6051 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6052 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6053 mPointerGesture.currentGestureProperties[0].clear();
6054 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6055 mPointerGesture.currentGestureProperties[0].toolType =
6056 AMOTION_EVENT_TOOL_TYPE_FINGER;
6057 mPointerGesture.currentGestureCoords[0].clear();
6058 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6059 mPointerGesture.referenceGestureX);
6060 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6061 mPointerGesture.referenceGestureY);
6062 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6063 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6064 // FREEFORM mode.
6065#if DEBUG_GESTURES
6066 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6067 "activeGestureId=%d, currentTouchPointerCount=%d",
6068 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6069#endif
6070 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6071
6072 mPointerGesture.currentGestureIdBits.clear();
6073
6074 BitSet32 mappedTouchIdBits;
6075 BitSet32 usedGestureIdBits;
6076 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6077 // Initially, assign the active gesture id to the active touch point
6078 // if there is one. No other touch id bits are mapped yet.
6079 if (!*outCancelPreviousGesture) {
6080 mappedTouchIdBits.markBit(activeTouchId);
6081 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6082 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6083 mPointerGesture.activeGestureId;
6084 } else {
6085 mPointerGesture.activeGestureId = -1;
6086 }
6087 } else {
6088 // Otherwise, assume we mapped all touches from the previous frame.
6089 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006090 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6091 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006092 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6093
6094 // Check whether we need to choose a new active gesture id because the
6095 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006096 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6097 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006098 !upTouchIdBits.isEmpty(); ) {
6099 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6100 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6101 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6102 mPointerGesture.activeGestureId = -1;
6103 break;
6104 }
6105 }
6106 }
6107
6108#if DEBUG_GESTURES
6109 ALOGD("Gestures: FREEFORM follow up "
6110 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6111 "activeGestureId=%d",
6112 mappedTouchIdBits.value, usedGestureIdBits.value,
6113 mPointerGesture.activeGestureId);
6114#endif
6115
Michael Wright842500e2015-03-13 17:32:02 -07006116 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117 for (uint32_t i = 0; i < currentFingerCount; i++) {
6118 uint32_t touchId = idBits.clearFirstMarkedBit();
6119 uint32_t gestureId;
6120 if (!mappedTouchIdBits.hasBit(touchId)) {
6121 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6122 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6123#if DEBUG_GESTURES
6124 ALOGD("Gestures: FREEFORM "
6125 "new mapping for touch id %d -> gesture id %d",
6126 touchId, gestureId);
6127#endif
6128 } else {
6129 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6130#if DEBUG_GESTURES
6131 ALOGD("Gestures: FREEFORM "
6132 "existing mapping for touch id %d -> gesture id %d",
6133 touchId, gestureId);
6134#endif
6135 }
6136 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6137 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6138
6139 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006140 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6142 * mPointerXZoomScale;
6143 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6144 * mPointerYZoomScale;
6145 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6146
6147 mPointerGesture.currentGestureProperties[i].clear();
6148 mPointerGesture.currentGestureProperties[i].id = gestureId;
6149 mPointerGesture.currentGestureProperties[i].toolType =
6150 AMOTION_EVENT_TOOL_TYPE_FINGER;
6151 mPointerGesture.currentGestureCoords[i].clear();
6152 mPointerGesture.currentGestureCoords[i].setAxisValue(
6153 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6154 mPointerGesture.currentGestureCoords[i].setAxisValue(
6155 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6156 mPointerGesture.currentGestureCoords[i].setAxisValue(
6157 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6158 }
6159
6160 if (mPointerGesture.activeGestureId < 0) {
6161 mPointerGesture.activeGestureId =
6162 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6163#if DEBUG_GESTURES
6164 ALOGD("Gestures: FREEFORM new "
6165 "activeGestureId=%d", mPointerGesture.activeGestureId);
6166#endif
6167 }
6168 }
6169 }
6170
Michael Wright842500e2015-03-13 17:32:02 -07006171 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172
6173#if DEBUG_GESTURES
6174 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6175 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6176 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6177 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6178 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6179 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6180 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6181 uint32_t id = idBits.clearFirstMarkedBit();
6182 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6183 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6184 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6185 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6186 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6187 id, index, properties.toolType,
6188 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6189 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6190 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6191 }
6192 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6193 uint32_t id = idBits.clearFirstMarkedBit();
6194 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6195 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6196 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6197 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6198 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6199 id, index, properties.toolType,
6200 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6201 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6202 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6203 }
6204#endif
6205 return true;
6206}
6207
6208void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6209 mPointerSimple.currentCoords.clear();
6210 mPointerSimple.currentProperties.clear();
6211
6212 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006213 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6214 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6215 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6216 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6217 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006218 mPointerController->setPosition(x, y);
6219
Michael Wright842500e2015-03-13 17:32:02 -07006220 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221 down = !hovering;
6222
6223 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006224 mPointerSimple.currentCoords.copyFrom(
6225 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6227 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6228 mPointerSimple.currentProperties.id = 0;
6229 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006230 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 } else {
6232 down = false;
6233 hovering = false;
6234 }
6235
6236 dispatchPointerSimple(when, policyFlags, down, hovering);
6237}
6238
6239void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6240 abortPointerSimple(when, policyFlags);
6241}
6242
6243void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6244 mPointerSimple.currentCoords.clear();
6245 mPointerSimple.currentProperties.clear();
6246
6247 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006248 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6249 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6250 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006251 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006252 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6253 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006254 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006255 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006256 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006257 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006258 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 * mPointerYMovementScale;
6260
6261 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6262 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6263
6264 mPointerController->move(deltaX, deltaY);
6265 } else {
6266 mPointerVelocityControl.reset();
6267 }
6268
Michael Wright842500e2015-03-13 17:32:02 -07006269 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 hovering = !down;
6271
6272 float x, y;
6273 mPointerController->getPosition(&x, &y);
6274 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006275 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6277 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6278 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6279 hovering ? 0.0f : 1.0f);
6280 mPointerSimple.currentProperties.id = 0;
6281 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006282 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 } else {
6284 mPointerVelocityControl.reset();
6285
6286 down = false;
6287 hovering = false;
6288 }
6289
6290 dispatchPointerSimple(when, policyFlags, down, hovering);
6291}
6292
6293void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6294 abortPointerSimple(when, policyFlags);
6295
6296 mPointerVelocityControl.reset();
6297}
6298
6299void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6300 bool down, bool hovering) {
6301 int32_t metaState = getContext()->getGlobalMetaState();
Andrii Kulian620f6d92018-09-14 16:51:59 -07006302 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303
Yi Kong9b14ac62018-07-17 13:48:38 -07006304 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305 if (down || hovering) {
6306 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6307 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006308 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6310 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6311 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6312 }
Andrii Kulian620f6d92018-09-14 16:51:59 -07006313 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 }
6315
6316 if (mPointerSimple.down && !down) {
6317 mPointerSimple.down = false;
6318
6319 // Send up.
Andrii Kulian620f6d92018-09-14 16:51:59 -07006320 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006321 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006322 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6324 mOrientedXPrecision, mOrientedYPrecision,
6325 mPointerSimple.downTime);
6326 getListener()->notifyMotion(&args);
6327 }
6328
6329 if (mPointerSimple.hovering && !hovering) {
6330 mPointerSimple.hovering = false;
6331
6332 // Send hover exit.
Andrii Kulian620f6d92018-09-14 16:51:59 -07006333 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006334 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006335 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6337 mOrientedXPrecision, mOrientedYPrecision,
6338 mPointerSimple.downTime);
6339 getListener()->notifyMotion(&args);
6340 }
6341
6342 if (down) {
6343 if (!mPointerSimple.down) {
6344 mPointerSimple.down = true;
6345 mPointerSimple.downTime = when;
6346
6347 // Send down.
Andrii Kulian620f6d92018-09-14 16:51:59 -07006348 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006349 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006350 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006351 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6352 mOrientedXPrecision, mOrientedYPrecision,
6353 mPointerSimple.downTime);
6354 getListener()->notifyMotion(&args);
6355 }
6356
6357 // Send move.
Andrii Kulian620f6d92018-09-14 16:51:59 -07006358 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006359 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006360 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6362 mOrientedXPrecision, mOrientedYPrecision,
6363 mPointerSimple.downTime);
6364 getListener()->notifyMotion(&args);
6365 }
6366
6367 if (hovering) {
6368 if (!mPointerSimple.hovering) {
6369 mPointerSimple.hovering = true;
6370
6371 // Send hover enter.
Andrii Kulian620f6d92018-09-14 16:51:59 -07006372 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006373 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006374 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006375 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6377 mOrientedXPrecision, mOrientedYPrecision,
6378 mPointerSimple.downTime);
6379 getListener()->notifyMotion(&args);
6380 }
6381
6382 // Send hover move.
Andrii Kulian620f6d92018-09-14 16:51:59 -07006383 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006384 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006385 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006386 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6388 mOrientedXPrecision, mOrientedYPrecision,
6389 mPointerSimple.downTime);
6390 getListener()->notifyMotion(&args);
6391 }
6392
Michael Wright842500e2015-03-13 17:32:02 -07006393 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6394 float vscroll = mCurrentRawState.rawVScroll;
6395 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006396 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6397 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398
6399 // Send scroll.
6400 PointerCoords pointerCoords;
6401 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6402 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6403 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6404
Andrii Kulian620f6d92018-09-14 16:51:59 -07006405 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006406 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006407 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 1, &mPointerSimple.currentProperties, &pointerCoords,
6409 mOrientedXPrecision, mOrientedYPrecision,
6410 mPointerSimple.downTime);
6411 getListener()->notifyMotion(&args);
6412 }
6413
6414 // Save state.
6415 if (down || hovering) {
6416 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6417 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6418 } else {
6419 mPointerSimple.reset();
6420 }
6421}
6422
6423void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6424 mPointerSimple.currentCoords.clear();
6425 mPointerSimple.currentProperties.clear();
6426
6427 dispatchPointerSimple(when, policyFlags, false, false);
6428}
6429
6430void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006431 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006432 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006434 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6435 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006436 PointerCoords pointerCoords[MAX_POINTERS];
6437 PointerProperties pointerProperties[MAX_POINTERS];
6438 uint32_t pointerCount = 0;
6439 while (!idBits.isEmpty()) {
6440 uint32_t id = idBits.clearFirstMarkedBit();
6441 uint32_t index = idToIndex[id];
6442 pointerProperties[pointerCount].copyFrom(properties[index]);
6443 pointerCoords[pointerCount].copyFrom(coords[index]);
6444
6445 if (changedId >= 0 && id == uint32_t(changedId)) {
6446 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6447 }
6448
6449 pointerCount += 1;
6450 }
6451
6452 ALOG_ASSERT(pointerCount != 0);
6453
6454 if (changedId >= 0 && pointerCount == 1) {
6455 // Replace initial down and final up action.
6456 // We can compare the action without masking off the changed pointer index
6457 // because we know the index is 0.
6458 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6459 action = AMOTION_EVENT_ACTION_DOWN;
6460 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6461 action = AMOTION_EVENT_ACTION_UP;
6462 } else {
6463 // Can't happen.
6464 ALOG_ASSERT(false);
6465 }
6466 }
Andrii Kulian620f6d92018-09-14 16:51:59 -07006467 int32_t displayId = mPointerController != nullptr ?
6468 mPointerController->getDisplayId() : mViewport.displayId;
6469 NotifyMotionArgs args(when, getDeviceId(), source, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006470 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006471 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472 xPrecision, yPrecision, downTime);
6473 getListener()->notifyMotion(&args);
6474}
6475
6476bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6477 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6478 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6479 BitSet32 idBits) const {
6480 bool changed = false;
6481 while (!idBits.isEmpty()) {
6482 uint32_t id = idBits.clearFirstMarkedBit();
6483 uint32_t inIndex = inIdToIndex[id];
6484 uint32_t outIndex = outIdToIndex[id];
6485
6486 const PointerProperties& curInProperties = inProperties[inIndex];
6487 const PointerCoords& curInCoords = inCoords[inIndex];
6488 PointerProperties& curOutProperties = outProperties[outIndex];
6489 PointerCoords& curOutCoords = outCoords[outIndex];
6490
6491 if (curInProperties != curOutProperties) {
6492 curOutProperties.copyFrom(curInProperties);
6493 changed = true;
6494 }
6495
6496 if (curInCoords != curOutCoords) {
6497 curOutCoords.copyFrom(curInCoords);
6498 changed = true;
6499 }
6500 }
6501 return changed;
6502}
6503
6504void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006505 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6507 }
6508}
6509
Jeff Brownc9aa6282015-02-11 19:03:28 -08006510void TouchInputMapper::cancelTouch(nsecs_t when) {
6511 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006512 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006513}
6514
Michael Wrightd02c5b62014-02-10 15:10:22 -08006515bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006516 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006517 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006519 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6520 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6521 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522}
6523
6524const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6525 int32_t x, int32_t y) {
6526 size_t numVirtualKeys = mVirtualKeys.size();
6527 for (size_t i = 0; i < numVirtualKeys; i++) {
6528 const VirtualKey& virtualKey = mVirtualKeys[i];
6529
6530#if DEBUG_VIRTUAL_KEYS
6531 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6532 "left=%d, top=%d, right=%d, bottom=%d",
6533 x, y,
6534 virtualKey.keyCode, virtualKey.scanCode,
6535 virtualKey.hitLeft, virtualKey.hitTop,
6536 virtualKey.hitRight, virtualKey.hitBottom);
6537#endif
6538
6539 if (virtualKey.isHit(x, y)) {
6540 return & virtualKey;
6541 }
6542 }
6543
Yi Kong9b14ac62018-07-17 13:48:38 -07006544 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006545}
6546
Michael Wright842500e2015-03-13 17:32:02 -07006547void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6548 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6549 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006550
Michael Wright842500e2015-03-13 17:32:02 -07006551 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552
6553 if (currentPointerCount == 0) {
6554 // No pointers to assign.
6555 return;
6556 }
6557
6558 if (lastPointerCount == 0) {
6559 // All pointers are new.
6560 for (uint32_t i = 0; i < currentPointerCount; i++) {
6561 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006562 current->rawPointerData.pointers[i].id = id;
6563 current->rawPointerData.idToIndex[id] = i;
6564 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565 }
6566 return;
6567 }
6568
6569 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006570 && current->rawPointerData.pointers[0].toolType
6571 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006573 uint32_t id = last->rawPointerData.pointers[0].id;
6574 current->rawPointerData.pointers[0].id = id;
6575 current->rawPointerData.idToIndex[id] = 0;
6576 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577 return;
6578 }
6579
6580 // General case.
6581 // We build a heap of squared euclidean distances between current and last pointers
6582 // associated with the current and last pointer indices. Then, we find the best
6583 // match (by distance) for each current pointer.
6584 // The pointers must have the same tool type but it is possible for them to
6585 // transition from hovering to touching or vice-versa while retaining the same id.
6586 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6587
6588 uint32_t heapSize = 0;
6589 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6590 currentPointerIndex++) {
6591 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6592 lastPointerIndex++) {
6593 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006594 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006596 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597 if (currentPointer.toolType == lastPointer.toolType) {
6598 int64_t deltaX = currentPointer.x - lastPointer.x;
6599 int64_t deltaY = currentPointer.y - lastPointer.y;
6600
6601 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6602
6603 // Insert new element into the heap (sift up).
6604 heap[heapSize].currentPointerIndex = currentPointerIndex;
6605 heap[heapSize].lastPointerIndex = lastPointerIndex;
6606 heap[heapSize].distance = distance;
6607 heapSize += 1;
6608 }
6609 }
6610 }
6611
6612 // Heapify
6613 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6614 startIndex -= 1;
6615 for (uint32_t parentIndex = startIndex; ;) {
6616 uint32_t childIndex = parentIndex * 2 + 1;
6617 if (childIndex >= heapSize) {
6618 break;
6619 }
6620
6621 if (childIndex + 1 < heapSize
6622 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6623 childIndex += 1;
6624 }
6625
6626 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6627 break;
6628 }
6629
6630 swap(heap[parentIndex], heap[childIndex]);
6631 parentIndex = childIndex;
6632 }
6633 }
6634
6635#if DEBUG_POINTER_ASSIGNMENT
6636 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6637 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006638 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6640 heap[i].distance);
6641 }
6642#endif
6643
6644 // Pull matches out by increasing order of distance.
6645 // To avoid reassigning pointers that have already been matched, the loop keeps track
6646 // of which last and current pointers have been matched using the matchedXXXBits variables.
6647 // It also tracks the used pointer id bits.
6648 BitSet32 matchedLastBits(0);
6649 BitSet32 matchedCurrentBits(0);
6650 BitSet32 usedIdBits(0);
6651 bool first = true;
6652 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6653 while (heapSize > 0) {
6654 if (first) {
6655 // The first time through the loop, we just consume the root element of
6656 // the heap (the one with smallest distance).
6657 first = false;
6658 } else {
6659 // Previous iterations consumed the root element of the heap.
6660 // Pop root element off of the heap (sift down).
6661 heap[0] = heap[heapSize];
6662 for (uint32_t parentIndex = 0; ;) {
6663 uint32_t childIndex = parentIndex * 2 + 1;
6664 if (childIndex >= heapSize) {
6665 break;
6666 }
6667
6668 if (childIndex + 1 < heapSize
6669 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6670 childIndex += 1;
6671 }
6672
6673 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6674 break;
6675 }
6676
6677 swap(heap[parentIndex], heap[childIndex]);
6678 parentIndex = childIndex;
6679 }
6680
6681#if DEBUG_POINTER_ASSIGNMENT
6682 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6683 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006684 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006685 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6686 heap[i].distance);
6687 }
6688#endif
6689 }
6690
6691 heapSize -= 1;
6692
6693 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6694 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6695
6696 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6697 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6698
6699 matchedCurrentBits.markBit(currentPointerIndex);
6700 matchedLastBits.markBit(lastPointerIndex);
6701
Michael Wright842500e2015-03-13 17:32:02 -07006702 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6703 current->rawPointerData.pointers[currentPointerIndex].id = id;
6704 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6705 current->rawPointerData.markIdBit(id,
6706 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006707 usedIdBits.markBit(id);
6708
6709#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006710 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6711 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006712 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6713#endif
6714 break;
6715 }
6716 }
6717
6718 // Assign fresh ids to pointers that were not matched in the process.
6719 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6720 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6721 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6722
Michael Wright842500e2015-03-13 17:32:02 -07006723 current->rawPointerData.pointers[currentPointerIndex].id = id;
6724 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6725 current->rawPointerData.markIdBit(id,
6726 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006727
6728#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006729 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006730#endif
6731 }
6732}
6733
6734int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6735 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6736 return AKEY_STATE_VIRTUAL;
6737 }
6738
6739 size_t numVirtualKeys = mVirtualKeys.size();
6740 for (size_t i = 0; i < numVirtualKeys; i++) {
6741 const VirtualKey& virtualKey = mVirtualKeys[i];
6742 if (virtualKey.keyCode == keyCode) {
6743 return AKEY_STATE_UP;
6744 }
6745 }
6746
6747 return AKEY_STATE_UNKNOWN;
6748}
6749
6750int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6751 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6752 return AKEY_STATE_VIRTUAL;
6753 }
6754
6755 size_t numVirtualKeys = mVirtualKeys.size();
6756 for (size_t i = 0; i < numVirtualKeys; i++) {
6757 const VirtualKey& virtualKey = mVirtualKeys[i];
6758 if (virtualKey.scanCode == scanCode) {
6759 return AKEY_STATE_UP;
6760 }
6761 }
6762
6763 return AKEY_STATE_UNKNOWN;
6764}
6765
6766bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6767 const int32_t* keyCodes, uint8_t* outFlags) {
6768 size_t numVirtualKeys = mVirtualKeys.size();
6769 for (size_t i = 0; i < numVirtualKeys; i++) {
6770 const VirtualKey& virtualKey = mVirtualKeys[i];
6771
6772 for (size_t i = 0; i < numCodes; i++) {
6773 if (virtualKey.keyCode == keyCodes[i]) {
6774 outFlags[i] = 1;
6775 }
6776 }
6777 }
6778
6779 return true;
6780}
6781
6782
6783// --- SingleTouchInputMapper ---
6784
6785SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6786 TouchInputMapper(device) {
6787}
6788
6789SingleTouchInputMapper::~SingleTouchInputMapper() {
6790}
6791
6792void SingleTouchInputMapper::reset(nsecs_t when) {
6793 mSingleTouchMotionAccumulator.reset(getDevice());
6794
6795 TouchInputMapper::reset(when);
6796}
6797
6798void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6799 TouchInputMapper::process(rawEvent);
6800
6801 mSingleTouchMotionAccumulator.process(rawEvent);
6802}
6803
Michael Wright842500e2015-03-13 17:32:02 -07006804void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006805 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006806 outState->rawPointerData.pointerCount = 1;
6807 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006808
6809 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6810 && (mTouchButtonAccumulator.isHovering()
6811 || (mRawPointerAxes.pressure.valid
6812 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006813 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006814
Michael Wright842500e2015-03-13 17:32:02 -07006815 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006816 outPointer.id = 0;
6817 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6818 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6819 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6820 outPointer.touchMajor = 0;
6821 outPointer.touchMinor = 0;
6822 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6823 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6824 outPointer.orientation = 0;
6825 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6826 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6827 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6828 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6829 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6830 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6831 }
6832 outPointer.isHovering = isHovering;
6833 }
6834}
6835
6836void SingleTouchInputMapper::configureRawPointerAxes() {
6837 TouchInputMapper::configureRawPointerAxes();
6838
6839 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6840 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6841 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6842 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6843 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6844 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6845 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6846}
6847
6848bool SingleTouchInputMapper::hasStylus() const {
6849 return mTouchButtonAccumulator.hasStylus();
6850}
6851
6852
6853// --- MultiTouchInputMapper ---
6854
6855MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6856 TouchInputMapper(device) {
6857}
6858
6859MultiTouchInputMapper::~MultiTouchInputMapper() {
6860}
6861
6862void MultiTouchInputMapper::reset(nsecs_t when) {
6863 mMultiTouchMotionAccumulator.reset(getDevice());
6864
6865 mPointerIdBits.clear();
6866
6867 TouchInputMapper::reset(when);
6868}
6869
6870void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6871 TouchInputMapper::process(rawEvent);
6872
6873 mMultiTouchMotionAccumulator.process(rawEvent);
6874}
6875
Michael Wright842500e2015-03-13 17:32:02 -07006876void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006877 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6878 size_t outCount = 0;
6879 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006880 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006881
6882 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6883 const MultiTouchMotionAccumulator::Slot* inSlot =
6884 mMultiTouchMotionAccumulator.getSlot(inIndex);
6885 if (!inSlot->isInUse()) {
6886 continue;
6887 }
6888
6889 if (outCount >= MAX_POINTERS) {
6890#if DEBUG_POINTERS
6891 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6892 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006893 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006894#endif
6895 break; // too many fingers!
6896 }
6897
Michael Wright842500e2015-03-13 17:32:02 -07006898 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006899 outPointer.x = inSlot->getX();
6900 outPointer.y = inSlot->getY();
6901 outPointer.pressure = inSlot->getPressure();
6902 outPointer.touchMajor = inSlot->getTouchMajor();
6903 outPointer.touchMinor = inSlot->getTouchMinor();
6904 outPointer.toolMajor = inSlot->getToolMajor();
6905 outPointer.toolMinor = inSlot->getToolMinor();
6906 outPointer.orientation = inSlot->getOrientation();
6907 outPointer.distance = inSlot->getDistance();
6908 outPointer.tiltX = 0;
6909 outPointer.tiltY = 0;
6910
6911 outPointer.toolType = inSlot->getToolType();
6912 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6913 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6914 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6915 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6916 }
6917 }
6918
6919 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6920 && (mTouchButtonAccumulator.isHovering()
6921 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6922 outPointer.isHovering = isHovering;
6923
6924 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006925 if (mHavePointerIds) {
6926 int32_t trackingId = inSlot->getTrackingId();
6927 int32_t id = -1;
6928 if (trackingId >= 0) {
6929 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6930 uint32_t n = idBits.clearFirstMarkedBit();
6931 if (mPointerTrackingIdMap[n] == trackingId) {
6932 id = n;
6933 }
6934 }
6935
6936 if (id < 0 && !mPointerIdBits.isFull()) {
6937 id = mPointerIdBits.markFirstUnmarkedBit();
6938 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006939 }
Michael Wright842500e2015-03-13 17:32:02 -07006940 }
gaoshang1a632de2016-08-24 10:23:50 +08006941 if (id < 0) {
6942 mHavePointerIds = false;
6943 outState->rawPointerData.clearIdBits();
6944 newPointerIdBits.clear();
6945 } else {
6946 outPointer.id = id;
6947 outState->rawPointerData.idToIndex[id] = outCount;
6948 outState->rawPointerData.markIdBit(id, isHovering);
6949 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006950 }
Michael Wright842500e2015-03-13 17:32:02 -07006951 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006952 outCount += 1;
6953 }
6954
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006955 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006956 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006957 mPointerIdBits = newPointerIdBits;
6958
6959 mMultiTouchMotionAccumulator.finishSync();
6960}
6961
6962void MultiTouchInputMapper::configureRawPointerAxes() {
6963 TouchInputMapper::configureRawPointerAxes();
6964
6965 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6966 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6967 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6968 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6969 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6970 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6971 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6972 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6973 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6974 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6975 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6976
6977 if (mRawPointerAxes.trackingId.valid
6978 && mRawPointerAxes.slot.valid
6979 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6980 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6981 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006982 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6983 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006984 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006985 slotCount = MAX_SLOTS;
6986 }
6987 mMultiTouchMotionAccumulator.configure(getDevice(),
6988 slotCount, true /*usingSlotsProtocol*/);
6989 } else {
6990 mMultiTouchMotionAccumulator.configure(getDevice(),
6991 MAX_POINTERS, false /*usingSlotsProtocol*/);
6992 }
6993}
6994
6995bool MultiTouchInputMapper::hasStylus() const {
6996 return mMultiTouchMotionAccumulator.hasStylus()
6997 || mTouchButtonAccumulator.hasStylus();
6998}
6999
Michael Wright842500e2015-03-13 17:32:02 -07007000// --- ExternalStylusInputMapper
7001
7002ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7003 InputMapper(device) {
7004
7005}
7006
7007uint32_t ExternalStylusInputMapper::getSources() {
7008 return AINPUT_SOURCE_STYLUS;
7009}
7010
7011void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7012 InputMapper::populateDeviceInfo(info);
7013 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7014 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7015}
7016
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007017void ExternalStylusInputMapper::dump(std::string& dump) {
7018 dump += INDENT2 "External Stylus Input Mapper:\n";
7019 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007020 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007021 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007022 dumpStylusState(dump, mStylusState);
7023}
7024
7025void ExternalStylusInputMapper::configure(nsecs_t when,
7026 const InputReaderConfiguration* config, uint32_t changes) {
7027 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7028 mTouchButtonAccumulator.configure(getDevice());
7029}
7030
7031void ExternalStylusInputMapper::reset(nsecs_t when) {
7032 InputDevice* device = getDevice();
7033 mSingleTouchMotionAccumulator.reset(device);
7034 mTouchButtonAccumulator.reset(device);
7035 InputMapper::reset(when);
7036}
7037
7038void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7039 mSingleTouchMotionAccumulator.process(rawEvent);
7040 mTouchButtonAccumulator.process(rawEvent);
7041
7042 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7043 sync(rawEvent->when);
7044 }
7045}
7046
7047void ExternalStylusInputMapper::sync(nsecs_t when) {
7048 mStylusState.clear();
7049
7050 mStylusState.when = when;
7051
Michael Wright45ccacf2015-04-21 19:01:58 +01007052 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7053 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7054 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7055 }
7056
Michael Wright842500e2015-03-13 17:32:02 -07007057 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7058 if (mRawPressureAxis.valid) {
7059 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7060 } else if (mTouchButtonAccumulator.isToolActive()) {
7061 mStylusState.pressure = 1.0f;
7062 } else {
7063 mStylusState.pressure = 0.0f;
7064 }
7065
7066 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007067
7068 mContext->dispatchExternalStylusState(mStylusState);
7069}
7070
Michael Wrightd02c5b62014-02-10 15:10:22 -08007071
7072// --- JoystickInputMapper ---
7073
7074JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7075 InputMapper(device) {
7076}
7077
7078JoystickInputMapper::~JoystickInputMapper() {
7079}
7080
7081uint32_t JoystickInputMapper::getSources() {
7082 return AINPUT_SOURCE_JOYSTICK;
7083}
7084
7085void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7086 InputMapper::populateDeviceInfo(info);
7087
7088 for (size_t i = 0; i < mAxes.size(); i++) {
7089 const Axis& axis = mAxes.valueAt(i);
7090 addMotionRange(axis.axisInfo.axis, axis, info);
7091
7092 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7093 addMotionRange(axis.axisInfo.highAxis, axis, info);
7094
7095 }
7096 }
7097}
7098
7099void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7100 InputDeviceInfo* info) {
7101 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7102 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7103 /* In order to ease the transition for developers from using the old axes
7104 * to the newer, more semantically correct axes, we'll continue to register
7105 * the old axes as duplicates of their corresponding new ones. */
7106 int32_t compatAxis = getCompatAxis(axisId);
7107 if (compatAxis >= 0) {
7108 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7109 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7110 }
7111}
7112
7113/* A mapping from axes the joystick actually has to the axes that should be
7114 * artificially created for compatibility purposes.
7115 * Returns -1 if no compatibility axis is needed. */
7116int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7117 switch(axis) {
7118 case AMOTION_EVENT_AXIS_LTRIGGER:
7119 return AMOTION_EVENT_AXIS_BRAKE;
7120 case AMOTION_EVENT_AXIS_RTRIGGER:
7121 return AMOTION_EVENT_AXIS_GAS;
7122 }
7123 return -1;
7124}
7125
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007126void JoystickInputMapper::dump(std::string& dump) {
7127 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007129 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007130 size_t numAxes = mAxes.size();
7131 for (size_t i = 0; i < numAxes; i++) {
7132 const Axis& axis = mAxes.valueAt(i);
7133 const char* label = getAxisLabel(axis.axisInfo.axis);
7134 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007135 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007136 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007137 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007138 }
7139 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7140 label = getAxisLabel(axis.axisInfo.highAxis);
7141 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007142 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007143 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007144 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007145 axis.axisInfo.splitValue);
7146 }
7147 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007148 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007149 }
7150
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007151 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 -08007152 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007153 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007154 "highScale=%0.5f, highOffset=%0.5f\n",
7155 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007156 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007157 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7158 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7159 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7160 }
7161}
7162
7163void JoystickInputMapper::configure(nsecs_t when,
7164 const InputReaderConfiguration* config, uint32_t changes) {
7165 InputMapper::configure(when, config, changes);
7166
7167 if (!changes) { // first time only
7168 // Collect all axes.
7169 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7170 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7171 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7172 continue; // axis must be claimed by a different device
7173 }
7174
7175 RawAbsoluteAxisInfo rawAxisInfo;
7176 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7177 if (rawAxisInfo.valid) {
7178 // Map axis.
7179 AxisInfo axisInfo;
7180 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7181 if (!explicitlyMapped) {
7182 // Axis is not explicitly mapped, will choose a generic axis later.
7183 axisInfo.mode = AxisInfo::MODE_NORMAL;
7184 axisInfo.axis = -1;
7185 }
7186
7187 // Apply flat override.
7188 int32_t rawFlat = axisInfo.flatOverride < 0
7189 ? rawAxisInfo.flat : axisInfo.flatOverride;
7190
7191 // Calculate scaling factors and limits.
7192 Axis axis;
7193 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7194 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7195 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7196 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7197 scale, 0.0f, highScale, 0.0f,
7198 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7199 rawAxisInfo.resolution * scale);
7200 } else if (isCenteredAxis(axisInfo.axis)) {
7201 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7202 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7203 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7204 scale, offset, scale, offset,
7205 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7206 rawAxisInfo.resolution * scale);
7207 } else {
7208 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7209 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7210 scale, 0.0f, scale, 0.0f,
7211 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7212 rawAxisInfo.resolution * scale);
7213 }
7214
7215 // To eliminate noise while the joystick is at rest, filter out small variations
7216 // in axis values up front.
7217 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7218
7219 mAxes.add(abs, axis);
7220 }
7221 }
7222
7223 // If there are too many axes, start dropping them.
7224 // Prefer to keep explicitly mapped axes.
7225 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007226 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007227 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007228 pruneAxes(true);
7229 pruneAxes(false);
7230 }
7231
7232 // Assign generic axis ids to remaining axes.
7233 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7234 size_t numAxes = mAxes.size();
7235 for (size_t i = 0; i < numAxes; i++) {
7236 Axis& axis = mAxes.editValueAt(i);
7237 if (axis.axisInfo.axis < 0) {
7238 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7239 && haveAxis(nextGenericAxisId)) {
7240 nextGenericAxisId += 1;
7241 }
7242
7243 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7244 axis.axisInfo.axis = nextGenericAxisId;
7245 nextGenericAxisId += 1;
7246 } else {
7247 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7248 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007249 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007250 mAxes.removeItemsAt(i--);
7251 numAxes -= 1;
7252 }
7253 }
7254 }
7255 }
7256}
7257
7258bool JoystickInputMapper::haveAxis(int32_t axisId) {
7259 size_t numAxes = mAxes.size();
7260 for (size_t i = 0; i < numAxes; i++) {
7261 const Axis& axis = mAxes.valueAt(i);
7262 if (axis.axisInfo.axis == axisId
7263 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7264 && axis.axisInfo.highAxis == axisId)) {
7265 return true;
7266 }
7267 }
7268 return false;
7269}
7270
7271void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7272 size_t i = mAxes.size();
7273 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7274 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7275 continue;
7276 }
7277 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007278 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007279 mAxes.removeItemsAt(i);
7280 }
7281}
7282
7283bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7284 switch (axis) {
7285 case AMOTION_EVENT_AXIS_X:
7286 case AMOTION_EVENT_AXIS_Y:
7287 case AMOTION_EVENT_AXIS_Z:
7288 case AMOTION_EVENT_AXIS_RX:
7289 case AMOTION_EVENT_AXIS_RY:
7290 case AMOTION_EVENT_AXIS_RZ:
7291 case AMOTION_EVENT_AXIS_HAT_X:
7292 case AMOTION_EVENT_AXIS_HAT_Y:
7293 case AMOTION_EVENT_AXIS_ORIENTATION:
7294 case AMOTION_EVENT_AXIS_RUDDER:
7295 case AMOTION_EVENT_AXIS_WHEEL:
7296 return true;
7297 default:
7298 return false;
7299 }
7300}
7301
7302void JoystickInputMapper::reset(nsecs_t when) {
7303 // Recenter all axes.
7304 size_t numAxes = mAxes.size();
7305 for (size_t i = 0; i < numAxes; i++) {
7306 Axis& axis = mAxes.editValueAt(i);
7307 axis.resetValue();
7308 }
7309
7310 InputMapper::reset(when);
7311}
7312
7313void JoystickInputMapper::process(const RawEvent* rawEvent) {
7314 switch (rawEvent->type) {
7315 case EV_ABS: {
7316 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7317 if (index >= 0) {
7318 Axis& axis = mAxes.editValueAt(index);
7319 float newValue, highNewValue;
7320 switch (axis.axisInfo.mode) {
7321 case AxisInfo::MODE_INVERT:
7322 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7323 * axis.scale + axis.offset;
7324 highNewValue = 0.0f;
7325 break;
7326 case AxisInfo::MODE_SPLIT:
7327 if (rawEvent->value < axis.axisInfo.splitValue) {
7328 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7329 * axis.scale + axis.offset;
7330 highNewValue = 0.0f;
7331 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7332 newValue = 0.0f;
7333 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7334 * axis.highScale + axis.highOffset;
7335 } else {
7336 newValue = 0.0f;
7337 highNewValue = 0.0f;
7338 }
7339 break;
7340 default:
7341 newValue = rawEvent->value * axis.scale + axis.offset;
7342 highNewValue = 0.0f;
7343 break;
7344 }
7345 axis.newValue = newValue;
7346 axis.highNewValue = highNewValue;
7347 }
7348 break;
7349 }
7350
7351 case EV_SYN:
7352 switch (rawEvent->code) {
7353 case SYN_REPORT:
7354 sync(rawEvent->when, false /*force*/);
7355 break;
7356 }
7357 break;
7358 }
7359}
7360
7361void JoystickInputMapper::sync(nsecs_t when, bool force) {
7362 if (!filterAxes(force)) {
7363 return;
7364 }
7365
7366 int32_t metaState = mContext->getGlobalMetaState();
7367 int32_t buttonState = 0;
7368
7369 PointerProperties pointerProperties;
7370 pointerProperties.clear();
7371 pointerProperties.id = 0;
7372 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7373
7374 PointerCoords pointerCoords;
7375 pointerCoords.clear();
7376
7377 size_t numAxes = mAxes.size();
7378 for (size_t i = 0; i < numAxes; i++) {
7379 const Axis& axis = mAxes.valueAt(i);
7380 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7381 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7382 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7383 axis.highCurrentValue);
7384 }
7385 }
7386
7387 // Moving a joystick axis should not wake the device because joysticks can
7388 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7389 // button will likely wake the device.
7390 // TODO: Use the input device configuration to control this behavior more finely.
7391 uint32_t policyFlags = 0;
7392
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007393 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7394 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007395 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007396 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007397 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007398 getListener()->notifyMotion(&args);
7399}
7400
7401void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7402 int32_t axis, float value) {
7403 pointerCoords->setAxisValue(axis, value);
7404 /* In order to ease the transition for developers from using the old axes
7405 * to the newer, more semantically correct axes, we'll continue to produce
7406 * values for the old axes as mirrors of the value of their corresponding
7407 * new axes. */
7408 int32_t compatAxis = getCompatAxis(axis);
7409 if (compatAxis >= 0) {
7410 pointerCoords->setAxisValue(compatAxis, value);
7411 }
7412}
7413
7414bool JoystickInputMapper::filterAxes(bool force) {
7415 bool atLeastOneSignificantChange = force;
7416 size_t numAxes = mAxes.size();
7417 for (size_t i = 0; i < numAxes; i++) {
7418 Axis& axis = mAxes.editValueAt(i);
7419 if (force || hasValueChangedSignificantly(axis.filter,
7420 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7421 axis.currentValue = axis.newValue;
7422 atLeastOneSignificantChange = true;
7423 }
7424 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7425 if (force || hasValueChangedSignificantly(axis.filter,
7426 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7427 axis.highCurrentValue = axis.highNewValue;
7428 atLeastOneSignificantChange = true;
7429 }
7430 }
7431 }
7432 return atLeastOneSignificantChange;
7433}
7434
7435bool JoystickInputMapper::hasValueChangedSignificantly(
7436 float filter, float newValue, float currentValue, float min, float max) {
7437 if (newValue != currentValue) {
7438 // Filter out small changes in value unless the value is converging on the axis
7439 // bounds or center point. This is intended to reduce the amount of information
7440 // sent to applications by particularly noisy joysticks (such as PS3).
7441 if (fabs(newValue - currentValue) > filter
7442 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7443 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7444 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7445 return true;
7446 }
7447 }
7448 return false;
7449}
7450
7451bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7452 float filter, float newValue, float currentValue, float thresholdValue) {
7453 float newDistance = fabs(newValue - thresholdValue);
7454 if (newDistance < filter) {
7455 float oldDistance = fabs(currentValue - thresholdValue);
7456 if (newDistance < oldDistance) {
7457 return true;
7458 }
7459 }
7460 return false;
7461}
7462
7463} // namespace android