blob: 1cbf78eb4310a3ee6431e40667b6b444b3afd91b [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.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080074static constexpr size_t MAX_SLOTS = 32;
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
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.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080078static constexpr 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.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080081static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
Michael Wright43fd19f2015-04-21 19:02:58 +010082
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080085static constexpr 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))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800239 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
240 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257// --- InputReader ---
258
Siarhei Vishniakou3bc7e092019-07-24 17:43:30 -0700259InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
260 const sp<InputReaderPolicyInterface>& policy,
261 const sp<InputListenerInterface>& listener)
262 : mContext(this),
263 mEventHub(eventHub),
264 mPolicy(policy),
265 mNextSequenceNum(1),
266 mGlobalMetaState(0),
267 mGeneration(1),
268 mDisableVirtualKeysTimeout(LLONG_MIN),
269 mNextTimeout(LLONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800270 mConfigurationChangesToRefresh(0) {
271 mQueuedListener = new QueuedInputListener(listener);
272
273 { // acquire lock
274 AutoMutex _l(mLock);
275
276 refreshConfigurationLocked(0);
277 updateGlobalMetaStateLocked();
278 } // release lock
279}
280
281InputReader::~InputReader() {
282 for (size_t i = 0; i < mDevices.size(); i++) {
283 delete mDevices.valueAt(i);
284 }
285}
286
287void InputReader::loopOnce() {
288 int32_t oldGeneration;
289 int32_t timeoutMillis;
290 bool inputDevicesChanged = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800291 std::vector<InputDeviceInfo> inputDevices;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800292 { // acquire lock
293 AutoMutex _l(mLock);
294
295 oldGeneration = mGeneration;
296 timeoutMillis = -1;
297
298 uint32_t changes = mConfigurationChangesToRefresh;
299 if (changes) {
300 mConfigurationChangesToRefresh = 0;
301 timeoutMillis = 0;
302 refreshConfigurationLocked(changes);
303 } else if (mNextTimeout != LLONG_MAX) {
304 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
305 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
306 }
307 } // release lock
308
309 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
310
311 { // acquire lock
312 AutoMutex _l(mLock);
313 mReaderIsAliveCondition.broadcast();
314
315 if (count) {
316 processEventsLocked(mEventBuffer, count);
317 }
318
319 if (mNextTimeout != LLONG_MAX) {
320 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
321 if (now >= mNextTimeout) {
322#if DEBUG_RAW_EVENTS
323 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
324#endif
325 mNextTimeout = LLONG_MAX;
326 timeoutExpiredLocked(now);
327 }
328 }
329
330 if (oldGeneration != mGeneration) {
331 inputDevicesChanged = true;
332 getInputDevicesLocked(inputDevices);
333 }
334 } // release lock
335
336 // Send out a message that the describes the changed input devices.
337 if (inputDevicesChanged) {
338 mPolicy->notifyInputDevicesChanged(inputDevices);
339 }
340
341 // Flush queued events out to the listener.
342 // This must happen outside of the lock because the listener could potentially call
343 // back into the InputReader's methods, such as getScanCodeState, or become blocked
344 // on another thread similarly waiting to acquire the InputReader lock thereby
345 // resulting in a deadlock. This situation is actually quite plausible because the
346 // listener is actually the input dispatcher, which calls into the window manager,
347 // which occasionally calls into the input reader.
348 mQueuedListener->flush();
349}
350
351void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
352 for (const RawEvent* rawEvent = rawEvents; count;) {
353 int32_t type = rawEvent->type;
354 size_t batchSize = 1;
355 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
356 int32_t deviceId = rawEvent->deviceId;
357 while (batchSize < count) {
358 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
359 || rawEvent[batchSize].deviceId != deviceId) {
360 break;
361 }
362 batchSize += 1;
363 }
364#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700365 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800366#endif
367 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
368 } else {
369 switch (rawEvent->type) {
370 case EventHubInterface::DEVICE_ADDED:
371 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
372 break;
373 case EventHubInterface::DEVICE_REMOVED:
374 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
375 break;
376 case EventHubInterface::FINISHED_DEVICE_SCAN:
377 handleConfigurationChangedLocked(rawEvent->when);
378 break;
379 default:
380 ALOG_ASSERT(false); // can't happen
381 break;
382 }
383 }
384 count -= batchSize;
385 rawEvent += batchSize;
386 }
387}
388
389void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
390 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
391 if (deviceIndex >= 0) {
392 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
393 return;
394 }
395
396 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
397 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
398 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
399
400 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
401 device->configure(when, &mConfig, 0);
402 device->reset(when);
403
404 if (device->isIgnored()) {
405 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100406 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800407 } else {
408 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100409 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800410 }
411
412 mDevices.add(deviceId, device);
413 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700414
415 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
416 notifyExternalStylusPresenceChanged();
417 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418}
419
420void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700421 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
423 if (deviceIndex < 0) {
424 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
425 return;
426 }
427
428 device = mDevices.valueAt(deviceIndex);
429 mDevices.removeItemsAt(deviceIndex, 1);
430 bumpGenerationLocked();
431
432 if (device->isIgnored()) {
433 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100434 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800435 } else {
436 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100437 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800438 }
439
Michael Wright842500e2015-03-13 17:32:02 -0700440 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
441 notifyExternalStylusPresenceChanged();
442 }
443
Michael Wrightd02c5b62014-02-10 15:10:22 -0800444 device->reset(when);
445 delete device;
446}
447
448InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
449 const InputDeviceIdentifier& identifier, uint32_t classes) {
450 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
451 controllerNumber, identifier, classes);
452
453 // External devices.
454 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
455 device->setExternal(true);
456 }
457
Tim Kilbourn063ff532015-04-08 10:26:18 -0700458 // Devices with mics.
459 if (classes & INPUT_DEVICE_CLASS_MIC) {
460 device->setMic(true);
461 }
462
Michael Wrightd02c5b62014-02-10 15:10:22 -0800463 // Switch-like devices.
464 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
465 device->addMapper(new SwitchInputMapper(device));
466 }
467
Prashant Malani1941ff52015-08-11 18:29:28 -0700468 // Scroll wheel-like devices.
469 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
470 device->addMapper(new RotaryEncoderInputMapper(device));
471 }
472
Michael Wrightd02c5b62014-02-10 15:10:22 -0800473 // Vibrator-like devices.
474 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
475 device->addMapper(new VibratorInputMapper(device));
476 }
477
478 // Keyboard-like devices.
479 uint32_t keyboardSource = 0;
480 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
481 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
482 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
483 }
484 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
485 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
486 }
487 if (classes & INPUT_DEVICE_CLASS_DPAD) {
488 keyboardSource |= AINPUT_SOURCE_DPAD;
489 }
490 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
491 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
492 }
493
494 if (keyboardSource != 0) {
495 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
496 }
497
498 // Cursor-like devices.
499 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
500 device->addMapper(new CursorInputMapper(device));
501 }
502
503 // Touchscreens and touchpad devices.
504 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
505 device->addMapper(new MultiTouchInputMapper(device));
506 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
507 device->addMapper(new SingleTouchInputMapper(device));
508 }
509
510 // Joystick-like devices.
511 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
512 device->addMapper(new JoystickInputMapper(device));
513 }
514
Michael Wright842500e2015-03-13 17:32:02 -0700515 // External stylus-like devices.
516 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
517 device->addMapper(new ExternalStylusInputMapper(device));
518 }
519
Michael Wrightd02c5b62014-02-10 15:10:22 -0800520 return device;
521}
522
523void InputReader::processEventsForDeviceLocked(int32_t deviceId,
524 const RawEvent* rawEvents, size_t count) {
525 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
526 if (deviceIndex < 0) {
527 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
528 return;
529 }
530
531 InputDevice* device = mDevices.valueAt(deviceIndex);
532 if (device->isIgnored()) {
533 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
534 return;
535 }
536
537 device->process(rawEvents, count);
538}
539
540void InputReader::timeoutExpiredLocked(nsecs_t when) {
541 for (size_t i = 0; i < mDevices.size(); i++) {
542 InputDevice* device = mDevices.valueAt(i);
543 if (!device->isIgnored()) {
544 device->timeoutExpired(when);
545 }
546 }
547}
548
549void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
550 // Reset global meta state because it depends on the list of all configured devices.
551 updateGlobalMetaStateLocked();
552
553 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800554 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800555 mQueuedListener->notifyConfigurationChanged(&args);
556}
557
558void InputReader::refreshConfigurationLocked(uint32_t changes) {
559 mPolicy->getReaderConfiguration(&mConfig);
560 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
561
562 if (changes) {
Siarhei Vishniakouc5ae0dc2019-07-10 15:51:18 -0700563 ALOGI("Reconfiguring input devices, changes=%s",
564 InputReaderConfiguration::changesToString(changes).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800565 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
566
567 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
568 mEventHub->requestReopenDevices();
569 } else {
570 for (size_t i = 0; i < mDevices.size(); i++) {
571 InputDevice* device = mDevices.valueAt(i);
572 device->configure(now, &mConfig, changes);
573 }
574 }
575 }
576}
577
578void InputReader::updateGlobalMetaStateLocked() {
579 mGlobalMetaState = 0;
580
581 for (size_t i = 0; i < mDevices.size(); i++) {
582 InputDevice* device = mDevices.valueAt(i);
583 mGlobalMetaState |= device->getMetaState();
584 }
585}
586
587int32_t InputReader::getGlobalMetaStateLocked() {
588 return mGlobalMetaState;
589}
590
Michael Wright842500e2015-03-13 17:32:02 -0700591void InputReader::notifyExternalStylusPresenceChanged() {
592 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
593}
594
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800595void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700596 for (size_t i = 0; i < mDevices.size(); i++) {
597 InputDevice* device = mDevices.valueAt(i);
598 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800599 InputDeviceInfo info;
600 device->getDeviceInfo(&info);
601 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700602 }
603 }
604}
605
606void InputReader::dispatchExternalStylusState(const StylusState& state) {
607 for (size_t i = 0; i < mDevices.size(); i++) {
608 InputDevice* device = mDevices.valueAt(i);
609 device->updateExternalStylusState(state);
610 }
611}
612
Michael Wrightd02c5b62014-02-10 15:10:22 -0800613void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
614 mDisableVirtualKeysTimeout = time;
615}
616
617bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
618 InputDevice* device, int32_t keyCode, int32_t scanCode) {
619 if (now < mDisableVirtualKeysTimeout) {
620 ALOGI("Dropping virtual key from device %s because virtual keys are "
621 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100622 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800623 (mDisableVirtualKeysTimeout - now) * 0.000001,
624 keyCode, scanCode);
625 return true;
626 } else {
627 return false;
628 }
629}
630
631void InputReader::fadePointerLocked() {
632 for (size_t i = 0; i < mDevices.size(); i++) {
633 InputDevice* device = mDevices.valueAt(i);
634 device->fadePointer();
635 }
636}
637
638void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
639 if (when < mNextTimeout) {
640 mNextTimeout = when;
641 mEventHub->wake();
642 }
643}
644
645int32_t InputReader::bumpGenerationLocked() {
646 return ++mGeneration;
647}
648
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800649void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800650 AutoMutex _l(mLock);
651 getInputDevicesLocked(outInputDevices);
652}
653
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800654void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800655 outInputDevices.clear();
656
657 size_t numDevices = mDevices.size();
658 for (size_t i = 0; i < numDevices; i++) {
659 InputDevice* device = mDevices.valueAt(i);
660 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800661 InputDeviceInfo info;
662 device->getDeviceInfo(&info);
663 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800664 }
665 }
666}
667
668int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
669 int32_t keyCode) {
670 AutoMutex _l(mLock);
671
672 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
673}
674
675int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
676 int32_t scanCode) {
677 AutoMutex _l(mLock);
678
679 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
680}
681
682int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
683 AutoMutex _l(mLock);
684
685 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
686}
687
688int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
689 GetStateFunc getStateFunc) {
690 int32_t result = AKEY_STATE_UNKNOWN;
691 if (deviceId >= 0) {
692 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
693 if (deviceIndex >= 0) {
694 InputDevice* device = mDevices.valueAt(deviceIndex);
695 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
696 result = (device->*getStateFunc)(sourceMask, code);
697 }
698 }
699 } else {
700 size_t numDevices = mDevices.size();
701 for (size_t i = 0; i < numDevices; i++) {
702 InputDevice* device = mDevices.valueAt(i);
703 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
704 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
705 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
706 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
707 if (currentResult >= AKEY_STATE_DOWN) {
708 return currentResult;
709 } else if (currentResult == AKEY_STATE_UP) {
710 result = currentResult;
711 }
712 }
713 }
714 }
715 return result;
716}
717
Andrii Kulian763a3a42016-03-08 10:46:16 -0800718void InputReader::toggleCapsLockState(int32_t deviceId) {
719 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
720 if (deviceIndex < 0) {
721 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
722 return;
723 }
724
725 InputDevice* device = mDevices.valueAt(deviceIndex);
726 if (device->isIgnored()) {
727 return;
728 }
729
730 device->updateMetaState(AKEYCODE_CAPS_LOCK);
731}
732
Michael Wrightd02c5b62014-02-10 15:10:22 -0800733bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
734 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
735 AutoMutex _l(mLock);
736
737 memset(outFlags, 0, numCodes);
738 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
739}
740
741bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
742 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
743 bool result = false;
744 if (deviceId >= 0) {
745 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
746 if (deviceIndex >= 0) {
747 InputDevice* device = mDevices.valueAt(deviceIndex);
748 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
749 result = device->markSupportedKeyCodes(sourceMask,
750 numCodes, keyCodes, outFlags);
751 }
752 }
753 } else {
754 size_t numDevices = mDevices.size();
755 for (size_t i = 0; i < numDevices; i++) {
756 InputDevice* device = mDevices.valueAt(i);
757 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
758 result |= device->markSupportedKeyCodes(sourceMask,
759 numCodes, keyCodes, outFlags);
760 }
761 }
762 }
763 return result;
764}
765
766void InputReader::requestRefreshConfiguration(uint32_t changes) {
767 AutoMutex _l(mLock);
768
769 if (changes) {
770 bool needWake = !mConfigurationChangesToRefresh;
771 mConfigurationChangesToRefresh |= changes;
772
773 if (needWake) {
774 mEventHub->wake();
775 }
776 }
777}
778
779void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
780 ssize_t repeat, int32_t token) {
781 AutoMutex _l(mLock);
782
783 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
784 if (deviceIndex >= 0) {
785 InputDevice* device = mDevices.valueAt(deviceIndex);
786 device->vibrate(pattern, patternSize, repeat, token);
787 }
788}
789
790void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
791 AutoMutex _l(mLock);
792
793 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
794 if (deviceIndex >= 0) {
795 InputDevice* device = mDevices.valueAt(deviceIndex);
796 device->cancelVibrate(token);
797 }
798}
799
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700800bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
801 AutoMutex _l(mLock);
802
803 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
804 if (deviceIndex >= 0) {
805 InputDevice* device = mDevices.valueAt(deviceIndex);
806 return device->isEnabled();
807 }
808 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
809 return false;
810}
811
Arthur Hungc23540e2018-11-29 20:42:11 +0800812bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
813 AutoMutex _l(mLock);
814
815 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
816 if (deviceIndex < 0) {
817 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
818 return false;
819 }
820
821 InputDevice* device = mDevices.valueAt(deviceIndex);
Arthur Hung2c9a3342019-07-23 14:18:59 +0800822 if (!device->isEnabled()) {
823 ALOGW("Ignoring disabled device %s", device->getName().c_str());
824 return false;
825 }
826
827 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplayId();
Arthur Hungc23540e2018-11-29 20:42:11 +0800828 // No associated display. By default, can dispatch to all displays.
829 if (!associatedDisplayId) {
830 return true;
831 }
832
833 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
Arthur Hung2c9a3342019-07-23 14:18:59 +0800834 ALOGW("Device %s is associated with display ADISPLAY_ID_NONE.", device->getName().c_str());
Arthur Hungc23540e2018-11-29 20:42:11 +0800835 return true;
836 }
837
838 return *associatedDisplayId == displayId;
839}
840
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800841void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842 AutoMutex _l(mLock);
843
844 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800845 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800847 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848
849 for (size_t i = 0; i < mDevices.size(); i++) {
850 mDevices.valueAt(i)->dump(dump);
851 }
852
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800853 dump += INDENT "Configuration:\n";
854 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
856 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800857 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100859 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800861 dump += "]\n";
862 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 mConfig.virtualKeyQuietTime * 0.000001f);
864
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
867 mConfig.pointerVelocityControlParameters.scale,
868 mConfig.pointerVelocityControlParameters.lowThreshold,
869 mConfig.pointerVelocityControlParameters.highThreshold,
870 mConfig.pointerVelocityControlParameters.acceleration);
871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
874 mConfig.wheelVelocityControlParameters.scale,
875 mConfig.wheelVelocityControlParameters.lowThreshold,
876 mConfig.wheelVelocityControlParameters.highThreshold,
877 mConfig.wheelVelocityControlParameters.acceleration);
878
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879 dump += StringPrintf(INDENT2 "PointerGesture:\n");
880 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800882 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800884 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800886 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800888 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800890 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800892 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800894 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800896 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800898 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800900 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800902 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800903 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700904
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800905 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700906 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800907}
908
909void InputReader::monitor() {
910 // Acquire and release the lock to ensure that the reader has not deadlocked.
911 mLock.lock();
912 mEventHub->wake();
913 mReaderIsAliveCondition.wait(mLock);
914 mLock.unlock();
915
916 // Check the EventHub
917 mEventHub->monitor();
918}
919
920
921// --- InputReader::ContextImpl ---
922
923InputReader::ContextImpl::ContextImpl(InputReader* reader) :
924 mReader(reader) {
925}
926
927void InputReader::ContextImpl::updateGlobalMetaState() {
928 // lock is already held by the input loop
929 mReader->updateGlobalMetaStateLocked();
930}
931
932int32_t InputReader::ContextImpl::getGlobalMetaState() {
933 // lock is already held by the input loop
934 return mReader->getGlobalMetaStateLocked();
935}
936
937void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
938 // lock is already held by the input loop
939 mReader->disableVirtualKeysUntilLocked(time);
940}
941
942bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
943 InputDevice* device, int32_t keyCode, int32_t scanCode) {
944 // lock is already held by the input loop
945 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
946}
947
948void InputReader::ContextImpl::fadePointer() {
949 // lock is already held by the input loop
950 mReader->fadePointerLocked();
951}
952
953void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
954 // lock is already held by the input loop
955 mReader->requestTimeoutAtTimeLocked(when);
956}
957
958int32_t InputReader::ContextImpl::bumpGeneration() {
959 // lock is already held by the input loop
960 return mReader->bumpGenerationLocked();
961}
962
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800963void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700964 // lock is already held by whatever called refreshConfigurationLocked
965 mReader->getExternalStylusDevicesLocked(outDevices);
966}
967
968void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
969 mReader->dispatchExternalStylusState(state);
970}
971
Michael Wrightd02c5b62014-02-10 15:10:22 -0800972InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
973 return mReader->mPolicy.get();
974}
975
976InputListenerInterface* InputReader::ContextImpl::getListener() {
977 return mReader->mQueuedListener.get();
978}
979
980EventHubInterface* InputReader::ContextImpl::getEventHub() {
981 return mReader->mEventHub.get();
982}
983
Prabir Pradhan42611e02018-11-27 14:04:02 -0800984uint32_t InputReader::ContextImpl::getNextSequenceNum() {
985 return (mReader->mNextSequenceNum)++;
986}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988// --- InputDevice ---
989
990InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
991 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
992 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
993 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700994 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995}
996
997InputDevice::~InputDevice() {
998 size_t numMappers = mMappers.size();
999 for (size_t i = 0; i < numMappers; i++) {
1000 delete mMappers[i];
1001 }
1002 mMappers.clear();
1003}
1004
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001005bool InputDevice::isEnabled() {
1006 return getEventHub()->isDeviceEnabled(mId);
1007}
1008
1009void InputDevice::setEnabled(bool enabled, nsecs_t when) {
Arthur Hung2c9a3342019-07-23 14:18:59 +08001010 if (enabled && mAssociatedDisplayPort && !mAssociatedViewport) {
1011 ALOGW("Cannot enable input device %s because it is associated with port %" PRIu8 ", "
1012 "but the corresponding viewport is not found",
1013 getName().c_str(), *mAssociatedDisplayPort);
1014 enabled = false;
1015 }
1016
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001017 if (isEnabled() == enabled) {
1018 return;
1019 }
1020
1021 if (enabled) {
1022 getEventHub()->enableDevice(mId);
1023 reset(when);
1024 } else {
1025 reset(when);
1026 getEventHub()->disableDevice(mId);
1027 }
1028 // Must change generation to flag this device as changed
1029 bumpGeneration();
1030}
1031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001032void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001034 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001036 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001037 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001038 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1039 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001040 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1041 if (mAssociatedDisplayPort) {
1042 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1043 } else {
1044 dump += "<none>\n";
1045 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001046 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1047 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1048 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001050 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1051 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001052 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001053 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001054 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001055 const char* label = getAxisLabel(range.axis);
1056 char name[32];
1057 if (label) {
1058 strncpy(name, label, sizeof(name));
1059 name[sizeof(name) - 1] = '\0';
1060 } else {
1061 snprintf(name, sizeof(name), "%d", range.axis);
1062 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001063 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1065 name, range.source, range.min, range.max, range.flat, range.fuzz,
1066 range.resolution);
1067 }
1068 }
1069
1070 size_t numMappers = mMappers.size();
1071 for (size_t i = 0; i < numMappers; i++) {
1072 InputMapper* mapper = mMappers[i];
1073 mapper->dump(dump);
1074 }
1075}
1076
1077void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001078 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001079}
1080
1081void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1082 mSources = 0;
1083
1084 if (!isIgnored()) {
1085 if (!changes) { // first time only
1086 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1087 }
1088
1089 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1090 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1091 sp<KeyCharacterMap> keyboardLayout =
1092 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1093 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1094 bumpGeneration();
1095 }
1096 }
1097 }
1098
1099 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1100 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001101 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001102 if (mAlias != alias) {
1103 mAlias = alias;
1104 bumpGeneration();
1105 }
1106 }
1107 }
1108
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001109 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
Siarhei Vishniakouc6f61192019-07-23 18:12:31 +00001110 auto it = config->disabledDevices.find(mId);
1111 bool enabled = it == config->disabledDevices.end();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001112 setEnabled(enabled, when);
1113 }
1114
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001115 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1116 // In most situations, no port will be specified.
1117 mAssociatedDisplayPort = std::nullopt;
Arthur Hung2c9a3342019-07-23 14:18:59 +08001118 mAssociatedViewport = std::nullopt;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001119 // Find the display port that corresponds to the current input port.
1120 const std::string& inputPort = mIdentifier.location;
1121 if (!inputPort.empty()) {
1122 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1123 const auto& displayPort = ports.find(inputPort);
1124 if (displayPort != ports.end()) {
1125 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1126 }
1127 }
Arthur Hung2c9a3342019-07-23 14:18:59 +08001128
1129 // If the device was explicitly disabled by the user, it would be present in the
1130 // "disabledDevices" list. If it is associated with a specific display, and it was not
1131 // explicitly disabled, then enable/disable the device based on whether we can find the
1132 // corresponding viewport.
1133 bool enabled = (config->disabledDevices.find(mId) == config->disabledDevices.end());
1134 if (mAssociatedDisplayPort) {
1135 mAssociatedViewport = config->getDisplayViewportByPort(*mAssociatedDisplayPort);
1136 if (!mAssociatedViewport) {
1137 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
1138 "but the corresponding viewport is not found.",
1139 getName().c_str(), *mAssociatedDisplayPort);
1140 enabled = false;
1141 }
1142 }
1143
1144 setEnabled(enabled, when);
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001145 }
1146
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001147 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001148 mapper->configure(when, config, changes);
1149 mSources |= mapper->getSources();
1150 }
1151 }
1152}
1153
1154void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001155 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001156 mapper->reset(when);
1157 }
1158
1159 mContext->updateGlobalMetaState();
1160
1161 notifyReset(when);
1162}
1163
1164void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1165 // Process all of the events in order for each mapper.
1166 // We cannot simply ask each mapper to process them in bulk because mappers may
1167 // have side-effects that must be interleaved. For example, joystick movement events and
1168 // gamepad button presses are handled by different mappers but they should be dispatched
1169 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001170 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001172 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1174 rawEvent->when);
1175#endif
1176
1177 if (mDropUntilNextSync) {
1178 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1179 mDropUntilNextSync = false;
1180#if DEBUG_RAW_EVENTS
1181 ALOGD("Recovered from input event buffer overrun.");
1182#endif
1183 } else {
1184#if DEBUG_RAW_EVENTS
1185 ALOGD("Dropped input event while waiting for next input sync.");
1186#endif
1187 }
1188 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001189 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001190 mDropUntilNextSync = true;
1191 reset(rawEvent->when);
1192 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001193 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001194 mapper->process(rawEvent);
1195 }
1196 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001197 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 }
1199}
1200
1201void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001202 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001203 mapper->timeoutExpired(when);
1204 }
1205}
1206
Michael Wright842500e2015-03-13 17:32:02 -07001207void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001208 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001209 mapper->updateExternalStylusState(state);
1210 }
1211}
1212
Michael Wrightd02c5b62014-02-10 15:10:22 -08001213void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1214 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001215 mIsExternal, mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001216 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001217 mapper->populateDeviceInfo(outDeviceInfo);
1218 }
1219}
1220
1221int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1222 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1223}
1224
1225int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1226 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1227}
1228
1229int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1230 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1231}
1232
1233int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1234 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001235 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001236 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1237 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1238 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1239 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1240 if (currentResult >= AKEY_STATE_DOWN) {
1241 return currentResult;
1242 } else if (currentResult == AKEY_STATE_UP) {
1243 result = currentResult;
1244 }
1245 }
1246 }
1247 return result;
1248}
1249
1250bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1251 const int32_t* keyCodes, uint8_t* outFlags) {
1252 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001253 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1255 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1256 }
1257 }
1258 return result;
1259}
1260
1261void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1262 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001263 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 mapper->vibrate(pattern, patternSize, repeat, token);
1265 }
1266}
1267
1268void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001269 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 mapper->cancelVibrate(token);
1271 }
1272}
1273
Jeff Brownc9aa6282015-02-11 19:03:28 -08001274void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001275 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001276 mapper->cancelTouch(when);
1277 }
1278}
1279
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280int32_t InputDevice::getMetaState() {
1281 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001282 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001283 result |= mapper->getMetaState();
1284 }
1285 return result;
1286}
1287
Andrii Kulian763a3a42016-03-08 10:46:16 -08001288void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001289 for (InputMapper* mapper : mMappers) {
1290 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001291 }
1292}
1293
Michael Wrightd02c5b62014-02-10 15:10:22 -08001294void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001295 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001296 mapper->fadePointer();
1297 }
1298}
1299
1300void InputDevice::bumpGeneration() {
1301 mGeneration = mContext->bumpGeneration();
1302}
1303
1304void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001305 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001306 mContext->getListener()->notifyDeviceReset(&args);
1307}
1308
Arthur Hung2c9a3342019-07-23 14:18:59 +08001309std::optional<int32_t> InputDevice::getAssociatedDisplayId() {
1310 // Check if we had associated to the specific display.
1311 if (mAssociatedViewport) {
1312 return mAssociatedViewport->displayId;
1313 }
1314
1315 // No associated display port, check if some InputMapper is associated.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001316 for (InputMapper* mapper : mMappers) {
Arthur Hung2c9a3342019-07-23 14:18:59 +08001317 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplayId();
Arthur Hungc23540e2018-11-29 20:42:11 +08001318 if (associatedDisplayId) {
1319 return associatedDisplayId;
1320 }
1321 }
1322
1323 return std::nullopt;
1324}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001325
1326// --- CursorButtonAccumulator ---
1327
1328CursorButtonAccumulator::CursorButtonAccumulator() {
1329 clearButtons();
1330}
1331
1332void CursorButtonAccumulator::reset(InputDevice* device) {
1333 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1334 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1335 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1336 mBtnBack = device->isKeyPressed(BTN_BACK);
1337 mBtnSide = device->isKeyPressed(BTN_SIDE);
1338 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1339 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1340 mBtnTask = device->isKeyPressed(BTN_TASK);
1341}
1342
1343void CursorButtonAccumulator::clearButtons() {
1344 mBtnLeft = 0;
1345 mBtnRight = 0;
1346 mBtnMiddle = 0;
1347 mBtnBack = 0;
1348 mBtnSide = 0;
1349 mBtnForward = 0;
1350 mBtnExtra = 0;
1351 mBtnTask = 0;
1352}
1353
1354void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1355 if (rawEvent->type == EV_KEY) {
1356 switch (rawEvent->code) {
1357 case BTN_LEFT:
1358 mBtnLeft = rawEvent->value;
1359 break;
1360 case BTN_RIGHT:
1361 mBtnRight = rawEvent->value;
1362 break;
1363 case BTN_MIDDLE:
1364 mBtnMiddle = rawEvent->value;
1365 break;
1366 case BTN_BACK:
1367 mBtnBack = rawEvent->value;
1368 break;
1369 case BTN_SIDE:
1370 mBtnSide = rawEvent->value;
1371 break;
1372 case BTN_FORWARD:
1373 mBtnForward = rawEvent->value;
1374 break;
1375 case BTN_EXTRA:
1376 mBtnExtra = rawEvent->value;
1377 break;
1378 case BTN_TASK:
1379 mBtnTask = rawEvent->value;
1380 break;
1381 }
1382 }
1383}
1384
1385uint32_t CursorButtonAccumulator::getButtonState() const {
1386 uint32_t result = 0;
1387 if (mBtnLeft) {
1388 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1389 }
1390 if (mBtnRight) {
1391 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1392 }
1393 if (mBtnMiddle) {
1394 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1395 }
1396 if (mBtnBack || mBtnSide) {
1397 result |= AMOTION_EVENT_BUTTON_BACK;
1398 }
1399 if (mBtnForward || mBtnExtra) {
1400 result |= AMOTION_EVENT_BUTTON_FORWARD;
1401 }
1402 return result;
1403}
1404
1405
1406// --- CursorMotionAccumulator ---
1407
1408CursorMotionAccumulator::CursorMotionAccumulator() {
1409 clearRelativeAxes();
1410}
1411
1412void CursorMotionAccumulator::reset(InputDevice* device) {
1413 clearRelativeAxes();
1414}
1415
1416void CursorMotionAccumulator::clearRelativeAxes() {
1417 mRelX = 0;
1418 mRelY = 0;
1419}
1420
1421void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1422 if (rawEvent->type == EV_REL) {
1423 switch (rawEvent->code) {
1424 case REL_X:
1425 mRelX = rawEvent->value;
1426 break;
1427 case REL_Y:
1428 mRelY = rawEvent->value;
1429 break;
1430 }
1431 }
1432}
1433
1434void CursorMotionAccumulator::finishSync() {
1435 clearRelativeAxes();
1436}
1437
1438
1439// --- CursorScrollAccumulator ---
1440
1441CursorScrollAccumulator::CursorScrollAccumulator() :
1442 mHaveRelWheel(false), mHaveRelHWheel(false) {
1443 clearRelativeAxes();
1444}
1445
1446void CursorScrollAccumulator::configure(InputDevice* device) {
1447 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1448 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1449}
1450
1451void CursorScrollAccumulator::reset(InputDevice* device) {
1452 clearRelativeAxes();
1453}
1454
1455void CursorScrollAccumulator::clearRelativeAxes() {
1456 mRelWheel = 0;
1457 mRelHWheel = 0;
1458}
1459
1460void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1461 if (rawEvent->type == EV_REL) {
1462 switch (rawEvent->code) {
1463 case REL_WHEEL:
1464 mRelWheel = rawEvent->value;
1465 break;
1466 case REL_HWHEEL:
1467 mRelHWheel = rawEvent->value;
1468 break;
1469 }
1470 }
1471}
1472
1473void CursorScrollAccumulator::finishSync() {
1474 clearRelativeAxes();
1475}
1476
1477
1478// --- TouchButtonAccumulator ---
1479
1480TouchButtonAccumulator::TouchButtonAccumulator() :
1481 mHaveBtnTouch(false), mHaveStylus(false) {
1482 clearButtons();
1483}
1484
1485void TouchButtonAccumulator::configure(InputDevice* device) {
1486 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1487 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1488 || device->hasKey(BTN_TOOL_RUBBER)
1489 || device->hasKey(BTN_TOOL_BRUSH)
1490 || device->hasKey(BTN_TOOL_PENCIL)
1491 || device->hasKey(BTN_TOOL_AIRBRUSH);
1492}
1493
1494void TouchButtonAccumulator::reset(InputDevice* device) {
1495 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1496 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001497 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1498 mBtnStylus2 =
1499 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1501 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1502 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1503 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1504 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1505 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1506 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1507 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1508 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1509 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1510 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1511}
1512
1513void TouchButtonAccumulator::clearButtons() {
1514 mBtnTouch = 0;
1515 mBtnStylus = 0;
1516 mBtnStylus2 = 0;
1517 mBtnToolFinger = 0;
1518 mBtnToolPen = 0;
1519 mBtnToolRubber = 0;
1520 mBtnToolBrush = 0;
1521 mBtnToolPencil = 0;
1522 mBtnToolAirbrush = 0;
1523 mBtnToolMouse = 0;
1524 mBtnToolLens = 0;
1525 mBtnToolDoubleTap = 0;
1526 mBtnToolTripleTap = 0;
1527 mBtnToolQuadTap = 0;
1528}
1529
1530void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1531 if (rawEvent->type == EV_KEY) {
1532 switch (rawEvent->code) {
1533 case BTN_TOUCH:
1534 mBtnTouch = rawEvent->value;
1535 break;
1536 case BTN_STYLUS:
1537 mBtnStylus = rawEvent->value;
1538 break;
1539 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001540 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001541 mBtnStylus2 = rawEvent->value;
1542 break;
1543 case BTN_TOOL_FINGER:
1544 mBtnToolFinger = rawEvent->value;
1545 break;
1546 case BTN_TOOL_PEN:
1547 mBtnToolPen = rawEvent->value;
1548 break;
1549 case BTN_TOOL_RUBBER:
1550 mBtnToolRubber = rawEvent->value;
1551 break;
1552 case BTN_TOOL_BRUSH:
1553 mBtnToolBrush = rawEvent->value;
1554 break;
1555 case BTN_TOOL_PENCIL:
1556 mBtnToolPencil = rawEvent->value;
1557 break;
1558 case BTN_TOOL_AIRBRUSH:
1559 mBtnToolAirbrush = rawEvent->value;
1560 break;
1561 case BTN_TOOL_MOUSE:
1562 mBtnToolMouse = rawEvent->value;
1563 break;
1564 case BTN_TOOL_LENS:
1565 mBtnToolLens = rawEvent->value;
1566 break;
1567 case BTN_TOOL_DOUBLETAP:
1568 mBtnToolDoubleTap = rawEvent->value;
1569 break;
1570 case BTN_TOOL_TRIPLETAP:
1571 mBtnToolTripleTap = rawEvent->value;
1572 break;
1573 case BTN_TOOL_QUADTAP:
1574 mBtnToolQuadTap = rawEvent->value;
1575 break;
1576 }
1577 }
1578}
1579
1580uint32_t TouchButtonAccumulator::getButtonState() const {
1581 uint32_t result = 0;
1582 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001583 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001584 }
1585 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001586 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001587 }
1588 return result;
1589}
1590
1591int32_t TouchButtonAccumulator::getToolType() const {
1592 if (mBtnToolMouse || mBtnToolLens) {
1593 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1594 }
1595 if (mBtnToolRubber) {
1596 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1597 }
1598 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1599 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1600 }
1601 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1602 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1603 }
1604 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1605}
1606
1607bool TouchButtonAccumulator::isToolActive() const {
1608 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1609 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1610 || mBtnToolMouse || mBtnToolLens
1611 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1612}
1613
1614bool TouchButtonAccumulator::isHovering() const {
1615 return mHaveBtnTouch && !mBtnTouch;
1616}
1617
1618bool TouchButtonAccumulator::hasStylus() const {
1619 return mHaveStylus;
1620}
1621
1622
1623// --- RawPointerAxes ---
1624
1625RawPointerAxes::RawPointerAxes() {
1626 clear();
1627}
1628
1629void RawPointerAxes::clear() {
1630 x.clear();
1631 y.clear();
1632 pressure.clear();
1633 touchMajor.clear();
1634 touchMinor.clear();
1635 toolMajor.clear();
1636 toolMinor.clear();
1637 orientation.clear();
1638 distance.clear();
1639 tiltX.clear();
1640 tiltY.clear();
1641 trackingId.clear();
1642 slot.clear();
1643}
1644
1645
1646// --- RawPointerData ---
1647
1648RawPointerData::RawPointerData() {
1649 clear();
1650}
1651
1652void RawPointerData::clear() {
1653 pointerCount = 0;
1654 clearIdBits();
1655}
1656
1657void RawPointerData::copyFrom(const RawPointerData& other) {
1658 pointerCount = other.pointerCount;
1659 hoveringIdBits = other.hoveringIdBits;
1660 touchingIdBits = other.touchingIdBits;
1661
1662 for (uint32_t i = 0; i < pointerCount; i++) {
1663 pointers[i] = other.pointers[i];
1664
1665 int id = pointers[i].id;
1666 idToIndex[id] = other.idToIndex[id];
1667 }
1668}
1669
1670void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1671 float x = 0, y = 0;
1672 uint32_t count = touchingIdBits.count();
1673 if (count) {
1674 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1675 uint32_t id = idBits.clearFirstMarkedBit();
1676 const Pointer& pointer = pointerForId(id);
1677 x += pointer.x;
1678 y += pointer.y;
1679 }
1680 x /= count;
1681 y /= count;
1682 }
1683 *outX = x;
1684 *outY = y;
1685}
1686
1687
1688// --- CookedPointerData ---
1689
1690CookedPointerData::CookedPointerData() {
1691 clear();
1692}
1693
1694void CookedPointerData::clear() {
1695 pointerCount = 0;
1696 hoveringIdBits.clear();
1697 touchingIdBits.clear();
1698}
1699
1700void CookedPointerData::copyFrom(const CookedPointerData& other) {
1701 pointerCount = other.pointerCount;
1702 hoveringIdBits = other.hoveringIdBits;
1703 touchingIdBits = other.touchingIdBits;
1704
1705 for (uint32_t i = 0; i < pointerCount; i++) {
1706 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1707 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1708
1709 int id = pointerProperties[i].id;
1710 idToIndex[id] = other.idToIndex[id];
1711 }
1712}
1713
1714
1715// --- SingleTouchMotionAccumulator ---
1716
1717SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1718 clearAbsoluteAxes();
1719}
1720
1721void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1722 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1723 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1724 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1725 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1726 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1727 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1728 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1729}
1730
1731void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1732 mAbsX = 0;
1733 mAbsY = 0;
1734 mAbsPressure = 0;
1735 mAbsToolWidth = 0;
1736 mAbsDistance = 0;
1737 mAbsTiltX = 0;
1738 mAbsTiltY = 0;
1739}
1740
1741void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1742 if (rawEvent->type == EV_ABS) {
1743 switch (rawEvent->code) {
1744 case ABS_X:
1745 mAbsX = rawEvent->value;
1746 break;
1747 case ABS_Y:
1748 mAbsY = rawEvent->value;
1749 break;
1750 case ABS_PRESSURE:
1751 mAbsPressure = rawEvent->value;
1752 break;
1753 case ABS_TOOL_WIDTH:
1754 mAbsToolWidth = rawEvent->value;
1755 break;
1756 case ABS_DISTANCE:
1757 mAbsDistance = rawEvent->value;
1758 break;
1759 case ABS_TILT_X:
1760 mAbsTiltX = rawEvent->value;
1761 break;
1762 case ABS_TILT_Y:
1763 mAbsTiltY = rawEvent->value;
1764 break;
1765 }
1766 }
1767}
1768
1769
1770// --- MultiTouchMotionAccumulator ---
1771
Atif Niyaz21da0ff2019-06-28 13:22:51 -07001772MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1773 : mCurrentSlot(-1),
1774 mSlots(nullptr),
1775 mSlotCount(0),
1776 mUsingSlotsProtocol(false),
1777 mHaveStylus(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778
1779MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1780 delete[] mSlots;
1781}
1782
1783void MultiTouchMotionAccumulator::configure(InputDevice* device,
1784 size_t slotCount, bool usingSlotsProtocol) {
1785 mSlotCount = slotCount;
1786 mUsingSlotsProtocol = usingSlotsProtocol;
1787 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1788
1789 delete[] mSlots;
1790 mSlots = new Slot[slotCount];
1791}
1792
1793void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1794 // Unfortunately there is no way to read the initial contents of the slots.
1795 // So when we reset the accumulator, we must assume they are all zeroes.
1796 if (mUsingSlotsProtocol) {
1797 // Query the driver for the current slot index and use it as the initial slot
1798 // before we start reading events from the device. It is possible that the
1799 // current slot index will not be the same as it was when the first event was
1800 // written into the evdev buffer, which means the input mapper could start
1801 // out of sync with the initial state of the events in the evdev buffer.
1802 // In the extremely unlikely case that this happens, the data from
1803 // two slots will be confused until the next ABS_MT_SLOT event is received.
1804 // This can cause the touch point to "jump", but at least there will be
1805 // no stuck touches.
1806 int32_t initialSlot;
1807 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1808 ABS_MT_SLOT, &initialSlot);
1809 if (status) {
1810 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1811 initialSlot = -1;
1812 }
1813 clearSlots(initialSlot);
1814 } else {
1815 clearSlots(-1);
1816 }
1817}
1818
1819void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1820 if (mSlots) {
1821 for (size_t i = 0; i < mSlotCount; i++) {
1822 mSlots[i].clear();
1823 }
1824 }
1825 mCurrentSlot = initialSlot;
1826}
1827
1828void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1829 if (rawEvent->type == EV_ABS) {
1830 bool newSlot = false;
1831 if (mUsingSlotsProtocol) {
1832 if (rawEvent->code == ABS_MT_SLOT) {
1833 mCurrentSlot = rawEvent->value;
1834 newSlot = true;
1835 }
1836 } else if (mCurrentSlot < 0) {
1837 mCurrentSlot = 0;
1838 }
1839
1840 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1841#if DEBUG_POINTERS
1842 if (newSlot) {
1843 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001844 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001845 mCurrentSlot, mSlotCount - 1);
1846 }
1847#endif
1848 } else {
1849 Slot* slot = &mSlots[mCurrentSlot];
1850
1851 switch (rawEvent->code) {
1852 case ABS_MT_POSITION_X:
1853 slot->mInUse = true;
1854 slot->mAbsMTPositionX = rawEvent->value;
1855 break;
1856 case ABS_MT_POSITION_Y:
1857 slot->mInUse = true;
1858 slot->mAbsMTPositionY = rawEvent->value;
1859 break;
1860 case ABS_MT_TOUCH_MAJOR:
1861 slot->mInUse = true;
1862 slot->mAbsMTTouchMajor = rawEvent->value;
1863 break;
1864 case ABS_MT_TOUCH_MINOR:
1865 slot->mInUse = true;
1866 slot->mAbsMTTouchMinor = rawEvent->value;
1867 slot->mHaveAbsMTTouchMinor = true;
1868 break;
1869 case ABS_MT_WIDTH_MAJOR:
1870 slot->mInUse = true;
1871 slot->mAbsMTWidthMajor = rawEvent->value;
1872 break;
1873 case ABS_MT_WIDTH_MINOR:
1874 slot->mInUse = true;
1875 slot->mAbsMTWidthMinor = rawEvent->value;
1876 slot->mHaveAbsMTWidthMinor = true;
1877 break;
1878 case ABS_MT_ORIENTATION:
1879 slot->mInUse = true;
1880 slot->mAbsMTOrientation = rawEvent->value;
1881 break;
1882 case ABS_MT_TRACKING_ID:
1883 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1884 // The slot is no longer in use but it retains its previous contents,
1885 // which may be reused for subsequent touches.
1886 slot->mInUse = false;
1887 } else {
1888 slot->mInUse = true;
1889 slot->mAbsMTTrackingId = rawEvent->value;
1890 }
1891 break;
1892 case ABS_MT_PRESSURE:
1893 slot->mInUse = true;
1894 slot->mAbsMTPressure = rawEvent->value;
1895 break;
1896 case ABS_MT_DISTANCE:
1897 slot->mInUse = true;
1898 slot->mAbsMTDistance = rawEvent->value;
1899 break;
1900 case ABS_MT_TOOL_TYPE:
1901 slot->mInUse = true;
1902 slot->mAbsMTToolType = rawEvent->value;
1903 slot->mHaveAbsMTToolType = true;
1904 break;
1905 }
1906 }
1907 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1908 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1909 mCurrentSlot += 1;
1910 }
1911}
1912
1913void MultiTouchMotionAccumulator::finishSync() {
1914 if (!mUsingSlotsProtocol) {
1915 clearSlots(-1);
1916 }
1917}
1918
1919bool MultiTouchMotionAccumulator::hasStylus() const {
1920 return mHaveStylus;
1921}
1922
1923
1924// --- MultiTouchMotionAccumulator::Slot ---
1925
1926MultiTouchMotionAccumulator::Slot::Slot() {
1927 clear();
1928}
1929
1930void MultiTouchMotionAccumulator::Slot::clear() {
1931 mInUse = false;
1932 mHaveAbsMTTouchMinor = false;
1933 mHaveAbsMTWidthMinor = false;
1934 mHaveAbsMTToolType = false;
1935 mAbsMTPositionX = 0;
1936 mAbsMTPositionY = 0;
1937 mAbsMTTouchMajor = 0;
1938 mAbsMTTouchMinor = 0;
1939 mAbsMTWidthMajor = 0;
1940 mAbsMTWidthMinor = 0;
1941 mAbsMTOrientation = 0;
1942 mAbsMTTrackingId = -1;
1943 mAbsMTPressure = 0;
1944 mAbsMTDistance = 0;
1945 mAbsMTToolType = 0;
1946}
1947
1948int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1949 if (mHaveAbsMTToolType) {
1950 switch (mAbsMTToolType) {
1951 case MT_TOOL_FINGER:
1952 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1953 case MT_TOOL_PEN:
1954 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1955 }
1956 }
1957 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1958}
1959
1960
1961// --- InputMapper ---
1962
1963InputMapper::InputMapper(InputDevice* device) :
1964 mDevice(device), mContext(device->getContext()) {
1965}
1966
1967InputMapper::~InputMapper() {
1968}
1969
1970void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1971 info->addSource(getSources());
1972}
1973
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001974void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975}
1976
1977void InputMapper::configure(nsecs_t when,
1978 const InputReaderConfiguration* config, uint32_t changes) {
1979}
1980
1981void InputMapper::reset(nsecs_t when) {
1982}
1983
1984void InputMapper::timeoutExpired(nsecs_t when) {
1985}
1986
1987int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1988 return AKEY_STATE_UNKNOWN;
1989}
1990
1991int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1992 return AKEY_STATE_UNKNOWN;
1993}
1994
1995int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1996 return AKEY_STATE_UNKNOWN;
1997}
1998
1999bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2000 const int32_t* keyCodes, uint8_t* outFlags) {
2001 return false;
2002}
2003
2004void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2005 int32_t token) {
2006}
2007
2008void InputMapper::cancelVibrate(int32_t token) {
2009}
2010
Jeff Brownc9aa6282015-02-11 19:03:28 -08002011void InputMapper::cancelTouch(nsecs_t when) {
2012}
2013
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014int32_t InputMapper::getMetaState() {
2015 return 0;
2016}
2017
Andrii Kulian763a3a42016-03-08 10:46:16 -08002018void InputMapper::updateMetaState(int32_t keyCode) {
2019}
2020
Michael Wright842500e2015-03-13 17:32:02 -07002021void InputMapper::updateExternalStylusState(const StylusState& state) {
2022
2023}
2024
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025void InputMapper::fadePointer() {
2026}
2027
2028status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2029 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2030}
2031
2032void InputMapper::bumpGeneration() {
2033 mDevice->bumpGeneration();
2034}
2035
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002036void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002037 const RawAbsoluteAxisInfo& axis, const char* name) {
2038 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002039 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002040 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2041 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002042 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002043 }
2044}
2045
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002046void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2047 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2048 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2049 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2050 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002051}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002052
2053// --- SwitchInputMapper ---
2054
2055SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002056 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057}
2058
2059SwitchInputMapper::~SwitchInputMapper() {
2060}
2061
2062uint32_t SwitchInputMapper::getSources() {
2063 return AINPUT_SOURCE_SWITCH;
2064}
2065
2066void SwitchInputMapper::process(const RawEvent* rawEvent) {
2067 switch (rawEvent->type) {
2068 case EV_SW:
2069 processSwitch(rawEvent->code, rawEvent->value);
2070 break;
2071
2072 case EV_SYN:
2073 if (rawEvent->code == SYN_REPORT) {
2074 sync(rawEvent->when);
2075 }
2076 }
2077}
2078
2079void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2080 if (switchCode >= 0 && switchCode < 32) {
2081 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002082 mSwitchValues |= 1 << switchCode;
2083 } else {
2084 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 }
2086 mUpdatedSwitchMask |= 1 << switchCode;
2087 }
2088}
2089
2090void SwitchInputMapper::sync(nsecs_t when) {
2091 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002092 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002093 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2094 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095 getListener()->notifySwitch(&args);
2096
Michael Wrightd02c5b62014-02-10 15:10:22 -08002097 mUpdatedSwitchMask = 0;
2098 }
2099}
2100
2101int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2102 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2103}
2104
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002105void SwitchInputMapper::dump(std::string& dump) {
2106 dump += INDENT2 "Switch Input Mapper:\n";
2107 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002108}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109
2110// --- VibratorInputMapper ---
2111
2112VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2113 InputMapper(device), mVibrating(false) {
2114}
2115
2116VibratorInputMapper::~VibratorInputMapper() {
2117}
2118
2119uint32_t VibratorInputMapper::getSources() {
2120 return 0;
2121}
2122
2123void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2124 InputMapper::populateDeviceInfo(info);
2125
2126 info->setVibrator(true);
2127}
2128
2129void VibratorInputMapper::process(const RawEvent* rawEvent) {
2130 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2131}
2132
2133void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2134 int32_t token) {
2135#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002136 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002137 for (size_t i = 0; i < patternSize; i++) {
2138 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002139 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002141 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002142 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002143 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002144 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002145#endif
2146
2147 mVibrating = true;
2148 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2149 mPatternSize = patternSize;
2150 mRepeat = repeat;
2151 mToken = token;
2152 mIndex = -1;
2153
2154 nextStep();
2155}
2156
2157void VibratorInputMapper::cancelVibrate(int32_t token) {
2158#if DEBUG_VIBRATOR
2159 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2160#endif
2161
2162 if (mVibrating && mToken == token) {
2163 stopVibrating();
2164 }
2165}
2166
2167void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2168 if (mVibrating) {
2169 if (when >= mNextStepTime) {
2170 nextStep();
2171 } else {
2172 getContext()->requestTimeoutAtTime(mNextStepTime);
2173 }
2174 }
2175}
2176
2177void VibratorInputMapper::nextStep() {
2178 mIndex += 1;
2179 if (size_t(mIndex) >= mPatternSize) {
2180 if (mRepeat < 0) {
2181 // We are done.
2182 stopVibrating();
2183 return;
2184 }
2185 mIndex = mRepeat;
2186 }
2187
2188 bool vibratorOn = mIndex & 1;
2189 nsecs_t duration = mPattern[mIndex];
2190 if (vibratorOn) {
2191#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002192 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193#endif
2194 getEventHub()->vibrate(getDeviceId(), duration);
2195 } else {
2196#if DEBUG_VIBRATOR
2197 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2198#endif
2199 getEventHub()->cancelVibrate(getDeviceId());
2200 }
2201 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2202 mNextStepTime = now + duration;
2203 getContext()->requestTimeoutAtTime(mNextStepTime);
2204#if DEBUG_VIBRATOR
2205 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2206#endif
2207}
2208
2209void VibratorInputMapper::stopVibrating() {
2210 mVibrating = false;
2211#if DEBUG_VIBRATOR
2212 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2213#endif
2214 getEventHub()->cancelVibrate(getDeviceId());
2215}
2216
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002217void VibratorInputMapper::dump(std::string& dump) {
2218 dump += INDENT2 "Vibrator Input Mapper:\n";
2219 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220}
2221
2222
2223// --- KeyboardInputMapper ---
2224
2225KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2226 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002227 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228}
2229
2230KeyboardInputMapper::~KeyboardInputMapper() {
2231}
2232
2233uint32_t KeyboardInputMapper::getSources() {
2234 return mSource;
2235}
2236
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002237int32_t KeyboardInputMapper::getOrientation() {
2238 if (mViewport) {
2239 return mViewport->orientation;
2240 }
2241 return DISPLAY_ORIENTATION_0;
2242}
2243
2244int32_t KeyboardInputMapper::getDisplayId() {
2245 if (mViewport) {
2246 return mViewport->displayId;
2247 }
2248 return ADISPLAY_ID_NONE;
2249}
2250
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2252 InputMapper::populateDeviceInfo(info);
2253
2254 info->setKeyboardType(mKeyboardType);
2255 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2256}
2257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002258void KeyboardInputMapper::dump(std::string& dump) {
2259 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002261 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002262 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002263 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2264 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2265 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266}
2267
Arthur Hung2c9a3342019-07-23 14:18:59 +08002268std::optional<DisplayViewport> KeyboardInputMapper::findViewport(
2269 nsecs_t when, const InputReaderConfiguration* config) {
2270 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
2271 if (displayPort) {
2272 // Find the viewport that contains the same port
2273 return mDevice->getAssociatedViewport();
2274 }
2275
2276 // No associated display defined, try to find default display if orientationAware.
2277 if (mParameters.orientationAware) {
2278 return config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
2279 }
2280
2281 return std::nullopt;
2282}
2283
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284void KeyboardInputMapper::configure(nsecs_t when,
2285 const InputReaderConfiguration* config, uint32_t changes) {
2286 InputMapper::configure(when, config, changes);
2287
2288 if (!changes) { // first time only
2289 // Configure basic parameters.
2290 configureParameters();
2291 }
2292
2293 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Arthur Hung2c9a3342019-07-23 14:18:59 +08002294 mViewport = findViewport(when, config);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295 }
2296}
2297
Ivan Podogovb9afef32017-02-13 15:34:32 +00002298static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2299 int32_t mapped = 0;
2300 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2301 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2302 if (stemKeyRotationMap[i][0] == keyCode) {
2303 stemKeyRotationMap[i][1] = mapped;
2304 return;
2305 }
2306 }
2307 }
2308}
2309
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310void KeyboardInputMapper::configureParameters() {
2311 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002312 const PropertyMap& config = getDevice()->getConfiguration();
2313 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002314 mParameters.orientationAware);
2315
Michael Wrightd02c5b62014-02-10 15:10:22 -08002316 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002317 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2318 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2319 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2320 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002321 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002322
2323 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002324 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002325 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002326}
2327
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002328void KeyboardInputMapper::dumpParameters(std::string& dump) {
2329 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002330 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002331 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002332 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002333 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334}
2335
2336void KeyboardInputMapper::reset(nsecs_t when) {
2337 mMetaState = AMETA_NONE;
2338 mDownTime = 0;
2339 mKeyDowns.clear();
2340 mCurrentHidUsage = 0;
2341
2342 resetLedState();
2343
2344 InputMapper::reset(when);
2345}
2346
2347void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2348 switch (rawEvent->type) {
2349 case EV_KEY: {
2350 int32_t scanCode = rawEvent->code;
2351 int32_t usageCode = mCurrentHidUsage;
2352 mCurrentHidUsage = 0;
2353
2354 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002355 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356 }
2357 break;
2358 }
2359 case EV_MSC: {
2360 if (rawEvent->code == MSC_SCAN) {
2361 mCurrentHidUsage = rawEvent->value;
2362 }
2363 break;
2364 }
2365 case EV_SYN: {
2366 if (rawEvent->code == SYN_REPORT) {
2367 mCurrentHidUsage = 0;
2368 }
2369 }
2370 }
2371}
2372
2373bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2374 return scanCode < BTN_MOUSE
2375 || scanCode >= KEY_OK
2376 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2377 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2378}
2379
Michael Wright58ba9882017-07-26 16:19:11 +01002380bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2381 switch (keyCode) {
2382 case AKEYCODE_MEDIA_PLAY:
2383 case AKEYCODE_MEDIA_PAUSE:
2384 case AKEYCODE_MEDIA_PLAY_PAUSE:
2385 case AKEYCODE_MUTE:
2386 case AKEYCODE_HEADSETHOOK:
2387 case AKEYCODE_MEDIA_STOP:
2388 case AKEYCODE_MEDIA_NEXT:
2389 case AKEYCODE_MEDIA_PREVIOUS:
2390 case AKEYCODE_MEDIA_REWIND:
2391 case AKEYCODE_MEDIA_RECORD:
2392 case AKEYCODE_MEDIA_FAST_FORWARD:
2393 case AKEYCODE_MEDIA_SKIP_FORWARD:
2394 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2395 case AKEYCODE_MEDIA_STEP_FORWARD:
2396 case AKEYCODE_MEDIA_STEP_BACKWARD:
2397 case AKEYCODE_MEDIA_AUDIO_TRACK:
2398 case AKEYCODE_VOLUME_UP:
2399 case AKEYCODE_VOLUME_DOWN:
2400 case AKEYCODE_VOLUME_MUTE:
2401 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2402 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2403 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2404 return true;
2405 }
2406 return false;
2407}
2408
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002409void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2410 int32_t usageCode) {
2411 int32_t keyCode;
2412 int32_t keyMetaState;
2413 uint32_t policyFlags;
2414
2415 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2416 &keyCode, &keyMetaState, &policyFlags)) {
2417 keyCode = AKEYCODE_UNKNOWN;
2418 keyMetaState = mMetaState;
2419 policyFlags = 0;
2420 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421
2422 if (down) {
2423 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002424 if (mParameters.orientationAware) {
2425 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 }
2427
2428 // Add key down.
2429 ssize_t keyDownIndex = findKeyDown(scanCode);
2430 if (keyDownIndex >= 0) {
2431 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002432 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 } else {
2434 // key down
2435 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2436 && mContext->shouldDropVirtualKey(when,
2437 getDevice(), keyCode, scanCode)) {
2438 return;
2439 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002440 if (policyFlags & POLICY_FLAG_GESTURE) {
2441 mDevice->cancelTouch(when);
2442 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002444 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002445 keyDown.keyCode = keyCode;
2446 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002447 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
2449
2450 mDownTime = when;
2451 } else {
2452 // Remove key down.
2453 ssize_t keyDownIndex = findKeyDown(scanCode);
2454 if (keyDownIndex >= 0) {
2455 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002456 keyCode = mKeyDowns[keyDownIndex].keyCode;
2457 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002458 } else {
2459 // key was not actually down
2460 ALOGI("Dropping key up from device %s because the key was not down. "
2461 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002462 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002463 return;
2464 }
2465 }
2466
Andrii Kulian763a3a42016-03-08 10:46:16 -08002467 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002468 // If global meta state changed send it along with the key.
2469 // If it has not changed then we'll use what keymap gave us,
2470 // since key replacement logic might temporarily reset a few
2471 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002472 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002473 }
2474
2475 nsecs_t downTime = mDownTime;
2476
2477 // Key down on external an keyboard should wake the device.
2478 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2479 // For internal keyboards, the key layout file should specify the policy flags for
2480 // each wake key individually.
2481 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002482 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002483 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002484 }
2485
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002486 if (mParameters.handlesKeyRepeat) {
2487 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2488 }
2489
Prabir Pradhan42611e02018-11-27 14:04:02 -08002490 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2491 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002492 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002493 getListener()->notifyKey(&args);
2494}
2495
2496ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2497 size_t n = mKeyDowns.size();
2498 for (size_t i = 0; i < n; i++) {
2499 if (mKeyDowns[i].scanCode == scanCode) {
2500 return i;
2501 }
2502 }
2503 return -1;
2504}
2505
2506int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2507 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2508}
2509
2510int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2511 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2512}
2513
2514bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2515 const int32_t* keyCodes, uint8_t* outFlags) {
2516 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2517}
2518
2519int32_t KeyboardInputMapper::getMetaState() {
2520 return mMetaState;
2521}
2522
Andrii Kulian763a3a42016-03-08 10:46:16 -08002523void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2524 updateMetaStateIfNeeded(keyCode, false);
2525}
2526
2527bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2528 int32_t oldMetaState = mMetaState;
2529 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2530 bool metaStateChanged = oldMetaState != newMetaState;
2531 if (metaStateChanged) {
2532 mMetaState = newMetaState;
2533 updateLedState(false);
2534
2535 getContext()->updateGlobalMetaState();
2536 }
2537
2538 return metaStateChanged;
2539}
2540
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541void KeyboardInputMapper::resetLedState() {
2542 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2543 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2544 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2545
2546 updateLedState(true);
2547}
2548
2549void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2550 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2551 ledState.on = false;
2552}
2553
2554void KeyboardInputMapper::updateLedState(bool reset) {
2555 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2556 AMETA_CAPS_LOCK_ON, reset);
2557 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2558 AMETA_NUM_LOCK_ON, reset);
2559 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2560 AMETA_SCROLL_LOCK_ON, reset);
2561}
2562
2563void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2564 int32_t led, int32_t modifier, bool reset) {
2565 if (ledState.avail) {
2566 bool desiredState = (mMetaState & modifier) != 0;
2567 if (reset || ledState.on != desiredState) {
2568 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2569 ledState.on = desiredState;
2570 }
2571 }
2572}
2573
Arthur Hung2c9a3342019-07-23 14:18:59 +08002574std::optional<int32_t> KeyboardInputMapper::getAssociatedDisplayId() {
2575 if (mViewport) {
2576 return std::make_optional(mViewport->displayId);
2577 }
2578 return std::nullopt;
2579}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580
2581// --- CursorInputMapper ---
2582
2583CursorInputMapper::CursorInputMapper(InputDevice* device) :
2584 InputMapper(device) {
2585}
2586
2587CursorInputMapper::~CursorInputMapper() {
2588}
2589
2590uint32_t CursorInputMapper::getSources() {
2591 return mSource;
2592}
2593
2594void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2595 InputMapper::populateDeviceInfo(info);
2596
2597 if (mParameters.mode == Parameters::MODE_POINTER) {
2598 float minX, minY, maxX, maxY;
2599 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2600 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2601 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2602 }
2603 } else {
2604 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2605 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2606 }
2607 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2608
2609 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2610 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2611 }
2612 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2613 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2614 }
2615}
2616
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002617void CursorInputMapper::dump(std::string& dump) {
2618 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002620 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2621 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2622 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2623 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2624 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002625 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002626 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002627 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002628 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2629 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2630 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2631 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2632 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2633 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634}
2635
2636void CursorInputMapper::configure(nsecs_t when,
2637 const InputReaderConfiguration* config, uint32_t changes) {
2638 InputMapper::configure(when, config, changes);
2639
2640 if (!changes) { // first time only
2641 mCursorScrollAccumulator.configure(getDevice());
2642
2643 // Configure basic parameters.
2644 configureParameters();
2645
2646 // Configure device mode.
2647 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002648 case Parameters::MODE_POINTER_RELATIVE:
2649 // Should not happen during first time configuration.
2650 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2651 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002652 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 case Parameters::MODE_POINTER:
2654 mSource = AINPUT_SOURCE_MOUSE;
2655 mXPrecision = 1.0f;
2656 mYPrecision = 1.0f;
2657 mXScale = 1.0f;
2658 mYScale = 1.0f;
2659 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2660 break;
2661 case Parameters::MODE_NAVIGATION:
2662 mSource = AINPUT_SOURCE_TRACKBALL;
2663 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2664 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2665 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2666 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2667 break;
2668 }
2669
2670 mVWheelScale = 1.0f;
2671 mHWheelScale = 1.0f;
2672 }
2673
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002674 if ((!changes && config->pointerCapture)
2675 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2676 if (config->pointerCapture) {
2677 if (mParameters.mode == Parameters::MODE_POINTER) {
2678 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2679 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2680 // Keep PointerController around in order to preserve the pointer position.
2681 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2682 } else {
2683 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2684 }
2685 } else {
2686 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2687 mParameters.mode = Parameters::MODE_POINTER;
2688 mSource = AINPUT_SOURCE_MOUSE;
2689 } else {
2690 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2691 }
2692 }
2693 bumpGeneration();
2694 if (changes) {
2695 getDevice()->notifyReset(when);
2696 }
2697 }
2698
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2700 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2701 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2702 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2703 }
2704
2705 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002706 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002708 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002709 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002710 if (internalViewport) {
2711 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002713 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002714
2715 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002716 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002717 getPolicy()->obtainPointerController(getDeviceId());
2718 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 bumpGeneration();
2720 }
2721}
2722
2723void CursorInputMapper::configureParameters() {
2724 mParameters.mode = Parameters::MODE_POINTER;
2725 String8 cursorModeString;
2726 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2727 if (cursorModeString == "navigation") {
2728 mParameters.mode = Parameters::MODE_NAVIGATION;
2729 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2730 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2731 }
2732 }
2733
2734 mParameters.orientationAware = false;
2735 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2736 mParameters.orientationAware);
2737
2738 mParameters.hasAssociatedDisplay = false;
2739 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2740 mParameters.hasAssociatedDisplay = true;
2741 }
2742}
2743
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002744void CursorInputMapper::dumpParameters(std::string& dump) {
2745 dump += INDENT3 "Parameters:\n";
2746 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002747 toString(mParameters.hasAssociatedDisplay));
2748
2749 switch (mParameters.mode) {
2750 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002751 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002752 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002753 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002754 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002755 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002757 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002758 break;
2759 default:
2760 ALOG_ASSERT(false);
2761 }
2762
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002763 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002764 toString(mParameters.orientationAware));
2765}
2766
2767void CursorInputMapper::reset(nsecs_t when) {
2768 mButtonState = 0;
2769 mDownTime = 0;
2770
2771 mPointerVelocityControl.reset();
2772 mWheelXVelocityControl.reset();
2773 mWheelYVelocityControl.reset();
2774
2775 mCursorButtonAccumulator.reset(getDevice());
2776 mCursorMotionAccumulator.reset(getDevice());
2777 mCursorScrollAccumulator.reset(getDevice());
2778
2779 InputMapper::reset(when);
2780}
2781
2782void CursorInputMapper::process(const RawEvent* rawEvent) {
2783 mCursorButtonAccumulator.process(rawEvent);
2784 mCursorMotionAccumulator.process(rawEvent);
2785 mCursorScrollAccumulator.process(rawEvent);
2786
2787 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2788 sync(rawEvent->when);
2789 }
2790}
2791
2792void CursorInputMapper::sync(nsecs_t when) {
2793 int32_t lastButtonState = mButtonState;
2794 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2795 mButtonState = currentButtonState;
2796
2797 bool wasDown = isPointerDown(lastButtonState);
2798 bool down = isPointerDown(currentButtonState);
2799 bool downChanged;
2800 if (!wasDown && down) {
2801 mDownTime = when;
2802 downChanged = true;
2803 } else if (wasDown && !down) {
2804 downChanged = true;
2805 } else {
2806 downChanged = false;
2807 }
2808 nsecs_t downTime = mDownTime;
2809 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002810 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2811 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812
2813 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2814 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2815 bool moved = deltaX != 0 || deltaY != 0;
2816
2817 // Rotate delta according to orientation if needed.
2818 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2819 && (deltaX != 0.0f || deltaY != 0.0f)) {
2820 rotateDelta(mOrientation, &deltaX, &deltaY);
2821 }
2822
2823 // Move the pointer.
2824 PointerProperties pointerProperties;
2825 pointerProperties.clear();
2826 pointerProperties.id = 0;
2827 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2828
2829 PointerCoords pointerCoords;
2830 pointerCoords.clear();
2831
2832 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2833 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2834 bool scrolled = vscroll != 0 || hscroll != 0;
2835
Yi Kong9b14ac62018-07-17 13:48:38 -07002836 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2837 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838
2839 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2840
2841 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002842 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2843 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002844 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 if (moved || scrolled || buttonsChanged) {
2846 mPointerController->setPresentation(
2847 PointerControllerInterface::PRESENTATION_POINTER);
2848
2849 if (moved) {
2850 mPointerController->move(deltaX, deltaY);
2851 }
2852
2853 if (buttonsChanged) {
2854 mPointerController->setButtonState(currentButtonState);
2855 }
2856
2857 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2858 }
2859
Garfield Tan00f511d2019-06-12 16:55:40 -07002860 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2861 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2862 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002863 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2864 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002865 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 } else {
2867 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2868 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2869 displayId = ADISPLAY_ID_NONE;
2870 }
2871
2872 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2873
2874 // Moving an external trackball or mouse should wake the device.
2875 // We don't do this for internal cursor devices to prevent them from waking up
2876 // the device in your pocket.
2877 // TODO: Use the input device configuration to control this behavior more finely.
2878 uint32_t policyFlags = 0;
2879 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002880 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 }
2882
2883 // Synthesize key down from buttons if needed.
2884 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002885 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
2887 // Send motion event.
2888 if (downChanged || moved || scrolled || buttonsChanged) {
2889 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002890 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 int32_t motionEventAction;
2892 if (downChanged) {
2893 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002894 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2896 } else {
2897 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2898 }
2899
Michael Wright7b159c92015-05-14 14:48:03 +01002900 if (buttonsReleased) {
2901 BitSet32 released(buttonsReleased);
2902 while (!released.isEmpty()) {
2903 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2904 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002905 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002906 mSource, displayId, policyFlags,
2907 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2908 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002909 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002910 &pointerCoords, mXPrecision, mYPrecision,
2911 xCursorPosition, yCursorPosition, downTime,
2912 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002913 getListener()->notifyMotion(&releaseArgs);
2914 }
2915 }
2916
Prabir Pradhan42611e02018-11-27 14:04:02 -08002917 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Garfield Tan00f511d2019-06-12 16:55:40 -07002918 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2919 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002920 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
Garfield Tan00f511d2019-06-12 16:55:40 -07002921 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2922 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 getListener()->notifyMotion(&args);
2924
Michael Wright7b159c92015-05-14 14:48:03 +01002925 if (buttonsPressed) {
2926 BitSet32 pressed(buttonsPressed);
2927 while (!pressed.isEmpty()) {
2928 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2929 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002930 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002931 mSource, displayId, policyFlags,
2932 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2933 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002934 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002935 &pointerCoords, mXPrecision, mYPrecision,
2936 xCursorPosition, yCursorPosition, downTime,
2937 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002938 getListener()->notifyMotion(&pressArgs);
2939 }
2940 }
2941
2942 ALOG_ASSERT(buttonState == currentButtonState);
2943
Michael Wrightd02c5b62014-02-10 15:10:22 -08002944 // Send hover move after UP to tell the application that the mouse is hovering now.
2945 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002946 && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002947 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2948 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2949 0, metaState, currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002950 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002951 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002952 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002953 getListener()->notifyMotion(&hoverArgs);
2954 }
2955
2956 // Send scroll events.
2957 if (scrolled) {
2958 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2959 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2960
Prabir Pradhan42611e02018-11-27 14:04:02 -08002961 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002962 mSource, displayId, policyFlags,
2963 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2964 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002965 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002966 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002967 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002968 getListener()->notifyMotion(&scrollArgs);
2969 }
2970 }
2971
2972 // Synthesize key up from buttons if needed.
2973 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002974 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002975
2976 mCursorMotionAccumulator.finishSync();
2977 mCursorScrollAccumulator.finishSync();
2978}
2979
2980int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2981 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2982 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2983 } else {
2984 return AKEY_STATE_UNKNOWN;
2985 }
2986}
2987
2988void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002989 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002990 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2991 }
2992}
2993
Arthur Hung2c9a3342019-07-23 14:18:59 +08002994std::optional<int32_t> CursorInputMapper::getAssociatedDisplayId() {
Arthur Hungc23540e2018-11-29 20:42:11 +08002995 if (mParameters.hasAssociatedDisplay) {
2996 if (mParameters.mode == Parameters::MODE_POINTER) {
2997 return std::make_optional(mPointerController->getDisplayId());
2998 } else {
2999 // If the device is orientationAware and not a mouse,
3000 // it expects to dispatch events to any display
3001 return std::make_optional(ADISPLAY_ID_NONE);
3002 }
3003 }
3004 return std::nullopt;
3005}
3006
Prashant Malani1941ff52015-08-11 18:29:28 -07003007// --- RotaryEncoderInputMapper ---
3008
3009RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01003010 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07003011 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
3012}
3013
3014RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
3015}
3016
3017uint32_t RotaryEncoderInputMapper::getSources() {
3018 return mSource;
3019}
3020
3021void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3022 InputMapper::populateDeviceInfo(info);
3023
3024 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08003025 float res = 0.0f;
3026 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
3027 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
3028 }
3029 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
3030 mScalingFactor)) {
3031 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
3032 "default to 1.0!\n");
3033 mScalingFactor = 1.0f;
3034 }
3035 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3036 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003037 }
3038}
3039
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003040void RotaryEncoderInputMapper::dump(std::string& dump) {
3041 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3042 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003043 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3044}
3045
3046void RotaryEncoderInputMapper::configure(nsecs_t when,
3047 const InputReaderConfiguration* config, uint32_t changes) {
3048 InputMapper::configure(when, config, changes);
3049 if (!changes) {
3050 mRotaryEncoderScrollAccumulator.configure(getDevice());
3051 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003052 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003053 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003054 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003055 if (internalViewport) {
3056 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003057 } else {
3058 mOrientation = DISPLAY_ORIENTATION_0;
3059 }
3060 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003061}
3062
3063void RotaryEncoderInputMapper::reset(nsecs_t when) {
3064 mRotaryEncoderScrollAccumulator.reset(getDevice());
3065
3066 InputMapper::reset(when);
3067}
3068
3069void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3070 mRotaryEncoderScrollAccumulator.process(rawEvent);
3071
3072 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3073 sync(rawEvent->when);
3074 }
3075}
3076
3077void RotaryEncoderInputMapper::sync(nsecs_t when) {
3078 PointerCoords pointerCoords;
3079 pointerCoords.clear();
3080
3081 PointerProperties pointerProperties;
3082 pointerProperties.clear();
3083 pointerProperties.id = 0;
3084 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3085
3086 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3087 bool scrolled = scroll != 0;
3088
3089 // This is not a pointer, so it's not associated with a display.
3090 int32_t displayId = ADISPLAY_ID_NONE;
3091
3092 // Moving the rotary encoder should wake the device (if specified).
3093 uint32_t policyFlags = 0;
3094 if (scrolled && getDevice()->isExternal()) {
3095 policyFlags |= POLICY_FLAG_WAKE;
3096 }
3097
Ivan Podogovad437252016-09-29 16:29:55 +01003098 if (mOrientation == DISPLAY_ORIENTATION_180) {
3099 scroll = -scroll;
3100 }
3101
Prashant Malani1941ff52015-08-11 18:29:28 -07003102 // Send motion event.
3103 if (scrolled) {
3104 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003105 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003106
Garfield Tan00f511d2019-06-12 16:55:40 -07003107 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3108 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3109 metaState, /* buttonState */ 0, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07003110 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
3111 &pointerCoords, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Garfield Tan00f511d2019-06-12 16:55:40 -07003112 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003113 getListener()->notifyMotion(&scrollArgs);
3114 }
3115
3116 mRotaryEncoderScrollAccumulator.finishSync();
3117}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003118
3119// --- TouchInputMapper ---
3120
3121TouchInputMapper::TouchInputMapper(InputDevice* device) :
3122 InputMapper(device),
3123 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3124 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003125 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003126 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3127}
3128
3129TouchInputMapper::~TouchInputMapper() {
3130}
3131
3132uint32_t TouchInputMapper::getSources() {
3133 return mSource;
3134}
3135
3136void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3137 InputMapper::populateDeviceInfo(info);
3138
3139 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3140 info->addMotionRange(mOrientedRanges.x);
3141 info->addMotionRange(mOrientedRanges.y);
3142 info->addMotionRange(mOrientedRanges.pressure);
3143
3144 if (mOrientedRanges.haveSize) {
3145 info->addMotionRange(mOrientedRanges.size);
3146 }
3147
3148 if (mOrientedRanges.haveTouchSize) {
3149 info->addMotionRange(mOrientedRanges.touchMajor);
3150 info->addMotionRange(mOrientedRanges.touchMinor);
3151 }
3152
3153 if (mOrientedRanges.haveToolSize) {
3154 info->addMotionRange(mOrientedRanges.toolMajor);
3155 info->addMotionRange(mOrientedRanges.toolMinor);
3156 }
3157
3158 if (mOrientedRanges.haveOrientation) {
3159 info->addMotionRange(mOrientedRanges.orientation);
3160 }
3161
3162 if (mOrientedRanges.haveDistance) {
3163 info->addMotionRange(mOrientedRanges.distance);
3164 }
3165
3166 if (mOrientedRanges.haveTilt) {
3167 info->addMotionRange(mOrientedRanges.tilt);
3168 }
3169
3170 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3171 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3172 0.0f);
3173 }
3174 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3175 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3176 0.0f);
3177 }
3178 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3179 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3180 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3181 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3182 x.fuzz, x.resolution);
3183 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3184 y.fuzz, y.resolution);
3185 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3186 x.fuzz, x.resolution);
3187 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3188 y.fuzz, y.resolution);
3189 }
3190 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3191 }
3192}
3193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003194void TouchInputMapper::dump(std::string& dump) {
3195 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 dumpParameters(dump);
3197 dumpVirtualKeys(dump);
3198 dumpRawPointerAxes(dump);
3199 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003200 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003201 dumpSurface(dump);
3202
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003203 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3204 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3205 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3206 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3207 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3208 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3209 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3210 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3211 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3212 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3213 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3214 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3215 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3216 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3217 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3218 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3219 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003221 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3222 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003223 mLastRawState.rawPointerData.pointerCount);
3224 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3225 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3228 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3229 "toolType=%d, isHovering=%s\n", i,
3230 pointer.id, pointer.x, pointer.y, pointer.pressure,
3231 pointer.touchMajor, pointer.touchMinor,
3232 pointer.toolMajor, pointer.toolMinor,
3233 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3234 pointer.toolType, toString(pointer.isHovering));
3235 }
3236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003237 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3238 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003239 mLastCookedState.cookedPointerData.pointerCount);
3240 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3241 const PointerProperties& pointerProperties =
3242 mLastCookedState.cookedPointerData.pointerProperties[i];
3243 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003244 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3246 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3247 "toolType=%d, isHovering=%s\n", i,
3248 pointerProperties.id,
3249 pointerCoords.getX(),
3250 pointerCoords.getY(),
3251 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3252 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3259 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003260 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261 }
3262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003263 dump += INDENT3 "Stylus Fusion:\n";
3264 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003265 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003266 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3267 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003268 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003269 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003270 dumpStylusState(dump, mExternalStylusState);
3271
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003273 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3274 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003276 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003277 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003278 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003280 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003282 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 mPointerGestureMaxSwipeWidth);
3284 }
3285}
3286
Santos Cordonfa5cf462017-04-05 10:37:00 -07003287const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3288 switch (deviceMode) {
3289 case DEVICE_MODE_DISABLED:
3290 return "disabled";
3291 case DEVICE_MODE_DIRECT:
3292 return "direct";
3293 case DEVICE_MODE_UNSCALED:
3294 return "unscaled";
3295 case DEVICE_MODE_NAVIGATION:
3296 return "navigation";
3297 case DEVICE_MODE_POINTER:
3298 return "pointer";
3299 }
3300 return "unknown";
3301}
3302
Michael Wrightd02c5b62014-02-10 15:10:22 -08003303void TouchInputMapper::configure(nsecs_t when,
3304 const InputReaderConfiguration* config, uint32_t changes) {
3305 InputMapper::configure(when, config, changes);
3306
3307 mConfig = *config;
3308
3309 if (!changes) { // first time only
3310 // Configure basic parameters.
3311 configureParameters();
3312
3313 // Configure common accumulators.
3314 mCursorScrollAccumulator.configure(getDevice());
3315 mTouchButtonAccumulator.configure(getDevice());
3316
3317 // Configure absolute axis information.
3318 configureRawPointerAxes();
3319
3320 // Prepare input device calibration.
3321 parseCalibration();
3322 resolveCalibration();
3323 }
3324
Michael Wright842500e2015-03-13 17:32:02 -07003325 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003326 // Update location calibration to reflect current settings
3327 updateAffineTransformation();
3328 }
3329
Michael Wrightd02c5b62014-02-10 15:10:22 -08003330 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3331 // Update pointer speed.
3332 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3333 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3334 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3335 }
3336
3337 bool resetNeeded = false;
3338 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3339 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003340 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3341 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 // Configure device sources, surface dimensions, orientation and
3343 // scaling factors.
3344 configureSurface(when, &resetNeeded);
3345 }
3346
3347 if (changes && resetNeeded) {
3348 // Send reset, unless this is the first time the device has been configured,
3349 // in which case the reader will call reset itself after all mappers are ready.
3350 getDevice()->notifyReset(when);
3351 }
3352}
3353
Michael Wright842500e2015-03-13 17:32:02 -07003354void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003355 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003356 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003357 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003358
3359 if (!mExternalStylusConnected) {
3360 resetExternalStylus();
3361 }
3362}
3363
Michael Wrightd02c5b62014-02-10 15:10:22 -08003364void TouchInputMapper::configureParameters() {
3365 // Use the pointer presentation mode for devices that do not support distinct
3366 // multitouch. The spot-based presentation relies on being able to accurately
3367 // locate two or more fingers on the touch pad.
3368 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003369 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370
3371 String8 gestureModeString;
3372 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3373 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003374 if (gestureModeString == "single-touch") {
3375 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3376 } else if (gestureModeString == "multi-touch") {
3377 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 } else if (gestureModeString != "default") {
3379 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3380 }
3381 }
3382
3383 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3384 // The device is a touch screen.
3385 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3386 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3387 // The device is a pointing device like a track pad.
3388 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3389 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3390 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3391 // The device is a cursor device with a touch pad attached.
3392 // By default don't use the touch pad to move the pointer.
3393 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3394 } else {
3395 // The device is a touch pad of unknown purpose.
3396 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3397 }
3398
3399 mParameters.hasButtonUnderPad=
3400 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3401
3402 String8 deviceTypeString;
3403 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3404 deviceTypeString)) {
3405 if (deviceTypeString == "touchScreen") {
3406 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3407 } else if (deviceTypeString == "touchPad") {
3408 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3409 } else if (deviceTypeString == "touchNavigation") {
3410 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3411 } else if (deviceTypeString == "pointer") {
3412 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3413 } else if (deviceTypeString != "default") {
3414 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3415 }
3416 }
3417
3418 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3419 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3420 mParameters.orientationAware);
3421
3422 mParameters.hasAssociatedDisplay = false;
3423 mParameters.associatedDisplayIsExternal = false;
3424 if (mParameters.orientationAware
3425 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3426 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3427 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003428 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3429 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003430 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003431 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003432 uniqueDisplayId);
3433 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003434 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003436 if (getDevice()->getAssociatedDisplayPort()) {
3437 mParameters.hasAssociatedDisplay = true;
3438 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003439
3440 // Initial downs on external touch devices should wake the device.
3441 // Normally we don't do this for internal touch screens to prevent them from waking
3442 // up in your pocket but you can enable it using the input device configuration.
3443 mParameters.wake = getDevice()->isExternal();
3444 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3445 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003446}
3447
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003448void TouchInputMapper::dumpParameters(std::string& dump) {
3449 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450
3451 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003452 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003453 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003455 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003456 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003457 break;
3458 default:
3459 assert(false);
3460 }
3461
3462 switch (mParameters.deviceType) {
3463 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003464 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003465 break;
3466 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003467 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003468 break;
3469 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003470 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 break;
3472 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003473 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 break;
3475 default:
3476 ALOG_ASSERT(false);
3477 }
3478
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003479 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003480 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003482 toString(mParameters.associatedDisplayIsExternal),
3483 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003484 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003485 toString(mParameters.orientationAware));
3486}
3487
3488void TouchInputMapper::configureRawPointerAxes() {
3489 mRawPointerAxes.clear();
3490}
3491
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003492void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3493 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003494 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3495 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3507}
3508
Michael Wright842500e2015-03-13 17:32:02 -07003509bool TouchInputMapper::hasExternalStylus() const {
3510 return mExternalStylusConnected;
3511}
3512
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003513/**
3514 * Determine which DisplayViewport to use.
3515 * 1. If display port is specified, return the matching viewport. If matching viewport not
3516 * found, then return.
3517 * 2. If a device has associated display, get the matching viewport by either unique id or by
3518 * the display type (internal or external).
3519 * 3. Otherwise, use a non-display viewport.
3520 */
3521std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3522 if (mParameters.hasAssociatedDisplay) {
3523 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3524 if (displayPort) {
3525 // Find the viewport that contains the same port
Arthur Hung2c9a3342019-07-23 14:18:59 +08003526 return mDevice->getAssociatedViewport();
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003527 }
3528
Arthur Hung2c9a3342019-07-23 14:18:59 +08003529 // Check if uniqueDisplayId is specified in idc file.
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003530 if (!mParameters.uniqueDisplayId.empty()) {
3531 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3532 }
3533
3534 ViewportType viewportTypeToUse;
3535 if (mParameters.associatedDisplayIsExternal) {
3536 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3537 } else {
3538 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3539 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003540
3541 std::optional<DisplayViewport> viewport =
3542 mConfig.getDisplayViewportByType(viewportTypeToUse);
3543 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3544 ALOGW("Input device %s should be associated with external display, "
3545 "fallback to internal one for the external viewport is not found.",
3546 getDeviceName().c_str());
3547 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3548 }
3549
3550 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003551 }
3552
Arthur Hung2c9a3342019-07-23 14:18:59 +08003553 // No associated display, return a non-display viewport.
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003554 DisplayViewport newViewport;
3555 // Raw width and height in the natural orientation.
3556 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3557 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3558 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3559 return std::make_optional(newViewport);
3560}
3561
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3563 int32_t oldDeviceMode = mDeviceMode;
3564
Michael Wright842500e2015-03-13 17:32:02 -07003565 resolveExternalStylusPresence();
3566
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 // Determine device mode.
3568 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3569 && mConfig.pointerGesturesEnabled) {
3570 mSource = AINPUT_SOURCE_MOUSE;
3571 mDeviceMode = DEVICE_MODE_POINTER;
3572 if (hasStylus()) {
3573 mSource |= AINPUT_SOURCE_STYLUS;
3574 }
3575 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3576 && mParameters.hasAssociatedDisplay) {
3577 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3578 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003579 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 mSource |= AINPUT_SOURCE_STYLUS;
3581 }
Michael Wright2f78b682015-06-12 15:25:08 +01003582 if (hasExternalStylus()) {
3583 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3584 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3586 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3587 mDeviceMode = DEVICE_MODE_NAVIGATION;
3588 } else {
3589 mSource = AINPUT_SOURCE_TOUCHPAD;
3590 mDeviceMode = DEVICE_MODE_UNSCALED;
3591 }
3592
3593 // Ensure we have valid X and Y axes.
3594 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003595 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003596 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003597 mDeviceMode = DEVICE_MODE_DISABLED;
3598 return;
3599 }
3600
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003601 // Get associated display dimensions.
3602 std::optional<DisplayViewport> newViewport = findViewport();
3603 if (!newViewport) {
3604 ALOGI("Touch device '%s' could not query the properties of its associated "
3605 "display. The device will be inoperable until the display size "
3606 "becomes available.",
3607 getDeviceName().c_str());
3608 mDeviceMode = DEVICE_MODE_DISABLED;
3609 return;
3610 }
3611
Michael Wrightd02c5b62014-02-10 15:10:22 -08003612 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003613 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3614 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003616 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003617 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003618 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619
3620 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3621 // Convert rotated viewport to natural surface coordinates.
3622 int32_t naturalLogicalWidth, naturalLogicalHeight;
3623 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3624 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3625 int32_t naturalDeviceWidth, naturalDeviceHeight;
3626 switch (mViewport.orientation) {
3627 case DISPLAY_ORIENTATION_90:
3628 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3629 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3630 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3631 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3632 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3633 naturalPhysicalTop = mViewport.physicalLeft;
3634 naturalDeviceWidth = mViewport.deviceHeight;
3635 naturalDeviceHeight = mViewport.deviceWidth;
3636 break;
3637 case DISPLAY_ORIENTATION_180:
3638 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3639 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3640 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3641 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3642 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3643 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3644 naturalDeviceWidth = mViewport.deviceWidth;
3645 naturalDeviceHeight = mViewport.deviceHeight;
3646 break;
3647 case DISPLAY_ORIENTATION_270:
3648 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3649 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3650 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3651 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3652 naturalPhysicalLeft = mViewport.physicalTop;
3653 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3654 naturalDeviceWidth = mViewport.deviceHeight;
3655 naturalDeviceHeight = mViewport.deviceWidth;
3656 break;
3657 case DISPLAY_ORIENTATION_0:
3658 default:
3659 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3660 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3661 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3662 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3663 naturalPhysicalLeft = mViewport.physicalLeft;
3664 naturalPhysicalTop = mViewport.physicalTop;
3665 naturalDeviceWidth = mViewport.deviceWidth;
3666 naturalDeviceHeight = mViewport.deviceHeight;
3667 break;
3668 }
3669
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003670 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3671 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3672 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3673 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3674 }
3675
Michael Wright358bcc72018-08-21 04:01:07 +01003676 mPhysicalWidth = naturalPhysicalWidth;
3677 mPhysicalHeight = naturalPhysicalHeight;
3678 mPhysicalLeft = naturalPhysicalLeft;
3679 mPhysicalTop = naturalPhysicalTop;
3680
Michael Wrightd02c5b62014-02-10 15:10:22 -08003681 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3682 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3683 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3684 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3685
3686 mSurfaceOrientation = mParameters.orientationAware ?
3687 mViewport.orientation : DISPLAY_ORIENTATION_0;
3688 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003689 mPhysicalWidth = rawWidth;
3690 mPhysicalHeight = rawHeight;
3691 mPhysicalLeft = 0;
3692 mPhysicalTop = 0;
3693
Michael Wrightd02c5b62014-02-10 15:10:22 -08003694 mSurfaceWidth = rawWidth;
3695 mSurfaceHeight = rawHeight;
3696 mSurfaceLeft = 0;
3697 mSurfaceTop = 0;
3698 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3699 }
3700 }
3701
3702 // If moving between pointer modes, need to reset some state.
3703 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3704 if (deviceModeChanged) {
3705 mOrientedRanges.clear();
3706 }
3707
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003708 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003709 if (mDeviceMode == DEVICE_MODE_POINTER ||
3710 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003711 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3713 }
3714 } else {
3715 mPointerController.clear();
3716 }
3717
3718 if (viewportChanged || deviceModeChanged) {
3719 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3720 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003721 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3723
3724 // Configure X and Y factors.
3725 mXScale = float(mSurfaceWidth) / rawWidth;
3726 mYScale = float(mSurfaceHeight) / rawHeight;
3727 mXTranslate = -mSurfaceLeft;
3728 mYTranslate = -mSurfaceTop;
3729 mXPrecision = 1.0f / mXScale;
3730 mYPrecision = 1.0f / mYScale;
3731
3732 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3733 mOrientedRanges.x.source = mSource;
3734 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3735 mOrientedRanges.y.source = mSource;
3736
3737 configureVirtualKeys();
3738
3739 // Scale factor for terms that are not oriented in a particular axis.
3740 // If the pixels are square then xScale == yScale otherwise we fake it
3741 // by choosing an average.
3742 mGeometricScale = avg(mXScale, mYScale);
3743
3744 // Size of diagonal axis.
3745 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3746
3747 // Size factors.
3748 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3749 if (mRawPointerAxes.touchMajor.valid
3750 && mRawPointerAxes.touchMajor.maxValue != 0) {
3751 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3752 } else if (mRawPointerAxes.toolMajor.valid
3753 && mRawPointerAxes.toolMajor.maxValue != 0) {
3754 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3755 } else {
3756 mSizeScale = 0.0f;
3757 }
3758
3759 mOrientedRanges.haveTouchSize = true;
3760 mOrientedRanges.haveToolSize = true;
3761 mOrientedRanges.haveSize = true;
3762
3763 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3764 mOrientedRanges.touchMajor.source = mSource;
3765 mOrientedRanges.touchMajor.min = 0;
3766 mOrientedRanges.touchMajor.max = diagonalSize;
3767 mOrientedRanges.touchMajor.flat = 0;
3768 mOrientedRanges.touchMajor.fuzz = 0;
3769 mOrientedRanges.touchMajor.resolution = 0;
3770
3771 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3772 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3773
3774 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3775 mOrientedRanges.toolMajor.source = mSource;
3776 mOrientedRanges.toolMajor.min = 0;
3777 mOrientedRanges.toolMajor.max = diagonalSize;
3778 mOrientedRanges.toolMajor.flat = 0;
3779 mOrientedRanges.toolMajor.fuzz = 0;
3780 mOrientedRanges.toolMajor.resolution = 0;
3781
3782 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3783 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3784
3785 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3786 mOrientedRanges.size.source = mSource;
3787 mOrientedRanges.size.min = 0;
3788 mOrientedRanges.size.max = 1.0;
3789 mOrientedRanges.size.flat = 0;
3790 mOrientedRanges.size.fuzz = 0;
3791 mOrientedRanges.size.resolution = 0;
3792 } else {
3793 mSizeScale = 0.0f;
3794 }
3795
3796 // Pressure factors.
3797 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003798 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003799 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3800 || mCalibration.pressureCalibration
3801 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3802 if (mCalibration.havePressureScale) {
3803 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003804 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003805 } else if (mRawPointerAxes.pressure.valid
3806 && mRawPointerAxes.pressure.maxValue != 0) {
3807 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3808 }
3809 }
3810
3811 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3812 mOrientedRanges.pressure.source = mSource;
3813 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003814 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003815 mOrientedRanges.pressure.flat = 0;
3816 mOrientedRanges.pressure.fuzz = 0;
3817 mOrientedRanges.pressure.resolution = 0;
3818
3819 // Tilt
3820 mTiltXCenter = 0;
3821 mTiltXScale = 0;
3822 mTiltYCenter = 0;
3823 mTiltYScale = 0;
3824 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3825 if (mHaveTilt) {
3826 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3827 mRawPointerAxes.tiltX.maxValue);
3828 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3829 mRawPointerAxes.tiltY.maxValue);
3830 mTiltXScale = M_PI / 180;
3831 mTiltYScale = M_PI / 180;
3832
3833 mOrientedRanges.haveTilt = true;
3834
3835 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3836 mOrientedRanges.tilt.source = mSource;
3837 mOrientedRanges.tilt.min = 0;
3838 mOrientedRanges.tilt.max = M_PI_2;
3839 mOrientedRanges.tilt.flat = 0;
3840 mOrientedRanges.tilt.fuzz = 0;
3841 mOrientedRanges.tilt.resolution = 0;
3842 }
3843
3844 // Orientation
3845 mOrientationScale = 0;
3846 if (mHaveTilt) {
3847 mOrientedRanges.haveOrientation = true;
3848
3849 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3850 mOrientedRanges.orientation.source = mSource;
3851 mOrientedRanges.orientation.min = -M_PI;
3852 mOrientedRanges.orientation.max = M_PI;
3853 mOrientedRanges.orientation.flat = 0;
3854 mOrientedRanges.orientation.fuzz = 0;
3855 mOrientedRanges.orientation.resolution = 0;
3856 } else if (mCalibration.orientationCalibration !=
3857 Calibration::ORIENTATION_CALIBRATION_NONE) {
3858 if (mCalibration.orientationCalibration
3859 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3860 if (mRawPointerAxes.orientation.valid) {
3861 if (mRawPointerAxes.orientation.maxValue > 0) {
3862 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3863 } else if (mRawPointerAxes.orientation.minValue < 0) {
3864 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3865 } else {
3866 mOrientationScale = 0;
3867 }
3868 }
3869 }
3870
3871 mOrientedRanges.haveOrientation = true;
3872
3873 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3874 mOrientedRanges.orientation.source = mSource;
3875 mOrientedRanges.orientation.min = -M_PI_2;
3876 mOrientedRanges.orientation.max = M_PI_2;
3877 mOrientedRanges.orientation.flat = 0;
3878 mOrientedRanges.orientation.fuzz = 0;
3879 mOrientedRanges.orientation.resolution = 0;
3880 }
3881
3882 // Distance
3883 mDistanceScale = 0;
3884 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3885 if (mCalibration.distanceCalibration
3886 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3887 if (mCalibration.haveDistanceScale) {
3888 mDistanceScale = mCalibration.distanceScale;
3889 } else {
3890 mDistanceScale = 1.0f;
3891 }
3892 }
3893
3894 mOrientedRanges.haveDistance = true;
3895
3896 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3897 mOrientedRanges.distance.source = mSource;
3898 mOrientedRanges.distance.min =
3899 mRawPointerAxes.distance.minValue * mDistanceScale;
3900 mOrientedRanges.distance.max =
3901 mRawPointerAxes.distance.maxValue * mDistanceScale;
3902 mOrientedRanges.distance.flat = 0;
3903 mOrientedRanges.distance.fuzz =
3904 mRawPointerAxes.distance.fuzz * mDistanceScale;
3905 mOrientedRanges.distance.resolution = 0;
3906 }
3907
3908 // Compute oriented precision, scales and ranges.
3909 // Note that the maximum value reported is an inclusive maximum value so it is one
3910 // unit less than the total width or height of surface.
3911 switch (mSurfaceOrientation) {
3912 case DISPLAY_ORIENTATION_90:
3913 case DISPLAY_ORIENTATION_270:
3914 mOrientedXPrecision = mYPrecision;
3915 mOrientedYPrecision = mXPrecision;
3916
3917 mOrientedRanges.x.min = mYTranslate;
3918 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3919 mOrientedRanges.x.flat = 0;
3920 mOrientedRanges.x.fuzz = 0;
3921 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3922
3923 mOrientedRanges.y.min = mXTranslate;
3924 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3925 mOrientedRanges.y.flat = 0;
3926 mOrientedRanges.y.fuzz = 0;
3927 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3928 break;
3929
3930 default:
3931 mOrientedXPrecision = mXPrecision;
3932 mOrientedYPrecision = mYPrecision;
3933
3934 mOrientedRanges.x.min = mXTranslate;
3935 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3936 mOrientedRanges.x.flat = 0;
3937 mOrientedRanges.x.fuzz = 0;
3938 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3939
3940 mOrientedRanges.y.min = mYTranslate;
3941 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3942 mOrientedRanges.y.flat = 0;
3943 mOrientedRanges.y.fuzz = 0;
3944 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3945 break;
3946 }
3947
Jason Gerecke71b16e82014-03-10 09:47:59 -07003948 // Location
3949 updateAffineTransformation();
3950
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 if (mDeviceMode == DEVICE_MODE_POINTER) {
3952 // Compute pointer gesture detection parameters.
3953 float rawDiagonal = hypotf(rawWidth, rawHeight);
3954 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3955
3956 // Scale movements such that one whole swipe of the touch pad covers a
3957 // given area relative to the diagonal size of the display when no acceleration
3958 // is applied.
3959 // Assume that the touch pad has a square aspect ratio such that movements in
3960 // X and Y of the same number of raw units cover the same physical distance.
3961 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3962 * displayDiagonal / rawDiagonal;
3963 mPointerYMovementScale = mPointerXMovementScale;
3964
3965 // Scale zooms to cover a smaller range of the display than movements do.
3966 // This value determines the area around the pointer that is affected by freeform
3967 // pointer gestures.
3968 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3969 * displayDiagonal / rawDiagonal;
3970 mPointerYZoomScale = mPointerXZoomScale;
3971
3972 // Max width between pointers to detect a swipe gesture is more than some fraction
3973 // of the diagonal axis of the touch pad. Touches that are wider than this are
3974 // translated into freeform gestures.
3975 mPointerGestureMaxSwipeWidth =
3976 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3977
3978 // Abort current pointer usages because the state has changed.
3979 abortPointerUsage(when, 0 /*policyFlags*/);
3980 }
3981
3982 // Inform the dispatcher about the changes.
3983 *outResetNeeded = true;
3984 bumpGeneration();
3985 }
3986}
3987
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003988void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003989 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003990 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3991 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3992 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3993 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003994 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3995 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3996 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3997 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003998 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999}
4000
4001void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004002 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
4004
4005 mVirtualKeys.clear();
4006
4007 if (virtualKeyDefinitions.size() == 0) {
4008 return;
4009 }
4010
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
4012 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08004013 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
4014 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004015
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004016 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
4017 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004018
4019 virtualKey.scanCode = virtualKeyDefinition.scanCode;
4020 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07004021 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004022 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07004023 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
4024 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004025 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
4026 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004027 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08004028 }
4029
4030 virtualKey.keyCode = keyCode;
4031 virtualKey.flags = flags;
4032
4033 // convert the key definition's display coordinates into touch coordinates for a hit box
4034 int32_t halfWidth = virtualKeyDefinition.width / 2;
4035 int32_t halfHeight = virtualKeyDefinition.height / 2;
4036
4037 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
4038 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
4039 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
4040 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
4041 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
4042 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
4043 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
4044 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004045 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004046 }
4047}
4048
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004049void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004050 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004051 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004052
4053 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004054 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004055 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004056 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4057 i, virtualKey.scanCode, virtualKey.keyCode,
4058 virtualKey.hitLeft, virtualKey.hitRight,
4059 virtualKey.hitTop, virtualKey.hitBottom);
4060 }
4061 }
4062}
4063
4064void TouchInputMapper::parseCalibration() {
4065 const PropertyMap& in = getDevice()->getConfiguration();
4066 Calibration& out = mCalibration;
4067
4068 // Size
4069 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4070 String8 sizeCalibrationString;
4071 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4072 if (sizeCalibrationString == "none") {
4073 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4074 } else if (sizeCalibrationString == "geometric") {
4075 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4076 } else if (sizeCalibrationString == "diameter") {
4077 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4078 } else if (sizeCalibrationString == "box") {
4079 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4080 } else if (sizeCalibrationString == "area") {
4081 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4082 } else if (sizeCalibrationString != "default") {
4083 ALOGW("Invalid value for touch.size.calibration: '%s'",
4084 sizeCalibrationString.string());
4085 }
4086 }
4087
4088 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4089 out.sizeScale);
4090 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4091 out.sizeBias);
4092 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4093 out.sizeIsSummed);
4094
4095 // Pressure
4096 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4097 String8 pressureCalibrationString;
4098 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4099 if (pressureCalibrationString == "none") {
4100 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4101 } else if (pressureCalibrationString == "physical") {
4102 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4103 } else if (pressureCalibrationString == "amplitude") {
4104 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4105 } else if (pressureCalibrationString != "default") {
4106 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4107 pressureCalibrationString.string());
4108 }
4109 }
4110
4111 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4112 out.pressureScale);
4113
4114 // Orientation
4115 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4116 String8 orientationCalibrationString;
4117 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4118 if (orientationCalibrationString == "none") {
4119 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4120 } else if (orientationCalibrationString == "interpolated") {
4121 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4122 } else if (orientationCalibrationString == "vector") {
4123 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4124 } else if (orientationCalibrationString != "default") {
4125 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4126 orientationCalibrationString.string());
4127 }
4128 }
4129
4130 // Distance
4131 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4132 String8 distanceCalibrationString;
4133 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4134 if (distanceCalibrationString == "none") {
4135 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4136 } else if (distanceCalibrationString == "scaled") {
4137 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4138 } else if (distanceCalibrationString != "default") {
4139 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4140 distanceCalibrationString.string());
4141 }
4142 }
4143
4144 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4145 out.distanceScale);
4146
4147 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4148 String8 coverageCalibrationString;
4149 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4150 if (coverageCalibrationString == "none") {
4151 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4152 } else if (coverageCalibrationString == "box") {
4153 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4154 } else if (coverageCalibrationString != "default") {
4155 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4156 coverageCalibrationString.string());
4157 }
4158 }
4159}
4160
4161void TouchInputMapper::resolveCalibration() {
4162 // Size
4163 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4164 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4165 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4166 }
4167 } else {
4168 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4169 }
4170
4171 // Pressure
4172 if (mRawPointerAxes.pressure.valid) {
4173 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4174 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4175 }
4176 } else {
4177 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4178 }
4179
4180 // Orientation
4181 if (mRawPointerAxes.orientation.valid) {
4182 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4183 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4184 }
4185 } else {
4186 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4187 }
4188
4189 // Distance
4190 if (mRawPointerAxes.distance.valid) {
4191 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4192 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4193 }
4194 } else {
4195 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4196 }
4197
4198 // Coverage
4199 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4200 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4201 }
4202}
4203
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204void TouchInputMapper::dumpCalibration(std::string& dump) {
4205 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206
4207 // Size
4208 switch (mCalibration.sizeCalibration) {
4209 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004210 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 break;
4212 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 break;
4215 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 break;
4218 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004222 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 break;
4224 default:
4225 ALOG_ASSERT(false);
4226 }
4227
4228 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 mCalibration.sizeScale);
4231 }
4232
4233 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004234 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004235 mCalibration.sizeBias);
4236 }
4237
4238 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004239 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 toString(mCalibration.sizeIsSummed));
4241 }
4242
4243 // Pressure
4244 switch (mCalibration.pressureCalibration) {
4245 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 break;
4248 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 break;
4251 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004252 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 break;
4254 default:
4255 ALOG_ASSERT(false);
4256 }
4257
4258 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004259 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004260 mCalibration.pressureScale);
4261 }
4262
4263 // Orientation
4264 switch (mCalibration.orientationCalibration) {
4265 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004266 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004267 break;
4268 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004269 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270 break;
4271 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004272 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 break;
4274 default:
4275 ALOG_ASSERT(false);
4276 }
4277
4278 // Distance
4279 switch (mCalibration.distanceCalibration) {
4280 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004281 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 break;
4283 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 break;
4286 default:
4287 ALOG_ASSERT(false);
4288 }
4289
4290 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004291 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 mCalibration.distanceScale);
4293 }
4294
4295 switch (mCalibration.coverageCalibration) {
4296 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004297 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 break;
4299 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004300 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004301 break;
4302 default:
4303 ALOG_ASSERT(false);
4304 }
4305}
4306
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004307void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4308 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004309
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004310 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4311 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4312 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4313 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4314 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4315 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004316}
4317
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004318void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004319 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4320 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004321}
4322
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323void TouchInputMapper::reset(nsecs_t when) {
4324 mCursorButtonAccumulator.reset(getDevice());
4325 mCursorScrollAccumulator.reset(getDevice());
4326 mTouchButtonAccumulator.reset(getDevice());
4327
4328 mPointerVelocityControl.reset();
4329 mWheelXVelocityControl.reset();
4330 mWheelYVelocityControl.reset();
4331
Michael Wright842500e2015-03-13 17:32:02 -07004332 mRawStatesPending.clear();
4333 mCurrentRawState.clear();
4334 mCurrentCookedState.clear();
4335 mLastRawState.clear();
4336 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337 mPointerUsage = POINTER_USAGE_NONE;
4338 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004339 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004340 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 mDownTime = 0;
4342
4343 mCurrentVirtualKey.down = false;
4344
4345 mPointerGesture.reset();
4346 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004347 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004348
Yi Kong9b14ac62018-07-17 13:48:38 -07004349 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4351 mPointerController->clearSpots();
4352 }
4353
4354 InputMapper::reset(when);
4355}
4356
Michael Wright842500e2015-03-13 17:32:02 -07004357void TouchInputMapper::resetExternalStylus() {
4358 mExternalStylusState.clear();
4359 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004360 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004361 mExternalStylusDataPending = false;
4362}
4363
Michael Wright43fd19f2015-04-21 19:02:58 +01004364void TouchInputMapper::clearStylusDataPendingFlags() {
4365 mExternalStylusDataPending = false;
4366 mExternalStylusFusionTimeout = LLONG_MAX;
4367}
4368
Michael Wrightd02c5b62014-02-10 15:10:22 -08004369void TouchInputMapper::process(const RawEvent* rawEvent) {
4370 mCursorButtonAccumulator.process(rawEvent);
4371 mCursorScrollAccumulator.process(rawEvent);
4372 mTouchButtonAccumulator.process(rawEvent);
4373
4374 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4375 sync(rawEvent->when);
4376 }
4377}
4378
4379void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004380 const RawState* last = mRawStatesPending.empty() ?
4381 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004382
4383 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004384 mRawStatesPending.emplace_back();
4385
4386 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004387 next->clear();
4388 next->when = when;
4389
Michael Wrightd02c5b62014-02-10 15:10:22 -08004390 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004391 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392 | mCursorButtonAccumulator.getButtonState();
4393
Michael Wright842500e2015-03-13 17:32:02 -07004394 // Sync scroll
4395 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4396 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004397 mCursorScrollAccumulator.finishSync();
4398
Michael Wright842500e2015-03-13 17:32:02 -07004399 // Sync touch
4400 syncTouch(when, next);
4401
4402 // Assign pointer ids.
4403 if (!mHavePointerIds) {
4404 assignPointerIds(last, next);
4405 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406
4407#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004408 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4409 "hovering ids 0x%08x -> 0x%08x",
4410 last->rawPointerData.pointerCount,
4411 next->rawPointerData.pointerCount,
4412 last->rawPointerData.touchingIdBits.value,
4413 next->rawPointerData.touchingIdBits.value,
4414 last->rawPointerData.hoveringIdBits.value,
4415 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004416#endif
4417
Michael Wright842500e2015-03-13 17:32:02 -07004418 processRawTouches(false /*timeout*/);
4419}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004420
Michael Wright842500e2015-03-13 17:32:02 -07004421void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004422 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4423 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004424 mCurrentRawState.clear();
4425 mRawStatesPending.clear();
4426 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004427 }
4428
Michael Wright842500e2015-03-13 17:32:02 -07004429 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4430 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4431 // touching the current state will only observe the events that have been dispatched to the
4432 // rest of the pipeline.
4433 const size_t N = mRawStatesPending.size();
4434 size_t count;
4435 for(count = 0; count < N; count++) {
4436 const RawState& next = mRawStatesPending[count];
4437
4438 // A failure to assign the stylus id means that we're waiting on stylus data
4439 // and so should defer the rest of the pipeline.
4440 if (assignExternalStylusId(next, timeout)) {
4441 break;
4442 }
4443
4444 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004445 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004446 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004447 if (mCurrentRawState.when < mLastRawState.when) {
4448 mCurrentRawState.when = mLastRawState.when;
4449 }
Michael Wright842500e2015-03-13 17:32:02 -07004450 cookAndDispatch(mCurrentRawState.when);
4451 }
4452 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004453 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004454 }
4455
Michael Wright842500e2015-03-13 17:32:02 -07004456 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004457 if (timeout) {
4458 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4459 clearStylusDataPendingFlags();
4460 mCurrentRawState.copyFrom(mLastRawState);
4461#if DEBUG_STYLUS_FUSION
4462 ALOGD("Timeout expired, synthesizing event with new stylus data");
4463#endif
4464 cookAndDispatch(when);
4465 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4466 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4467 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4468 }
Michael Wright842500e2015-03-13 17:32:02 -07004469 }
4470}
4471
4472void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4473 // Always start with a clean state.
4474 mCurrentCookedState.clear();
4475
4476 // Apply stylus buttons to current raw state.
4477 applyExternalStylusButtonState(when);
4478
4479 // Handle policy on initial down or hover events.
4480 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4481 && mCurrentRawState.rawPointerData.pointerCount != 0;
4482
4483 uint32_t policyFlags = 0;
4484 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4485 if (initialDown || buttonsPressed) {
4486 // If this is a touch screen, hide the pointer on an initial down.
4487 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4488 getContext()->fadePointer();
4489 }
4490
4491 if (mParameters.wake) {
4492 policyFlags |= POLICY_FLAG_WAKE;
4493 }
4494 }
4495
4496 // Consume raw off-screen touches before cooking pointer data.
4497 // If touches are consumed, subsequent code will not receive any pointer data.
4498 if (consumeRawTouches(when, policyFlags)) {
4499 mCurrentRawState.rawPointerData.clear();
4500 }
4501
4502 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4503 // with cooked pointer data that has the same ids and indices as the raw data.
4504 // The following code can use either the raw or cooked data, as needed.
4505 cookPointerData();
4506
4507 // Apply stylus pressure to current cooked state.
4508 applyExternalStylusTouchState(when);
4509
4510 // Synthesize key down from raw buttons if needed.
4511 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004512 mViewport.displayId, policyFlags,
4513 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004514
4515 // Dispatch the touches either directly or by translation through a pointer on screen.
4516 if (mDeviceMode == DEVICE_MODE_POINTER) {
4517 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4518 !idBits.isEmpty(); ) {
4519 uint32_t id = idBits.clearFirstMarkedBit();
4520 const RawPointerData::Pointer& pointer =
4521 mCurrentRawState.rawPointerData.pointerForId(id);
4522 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4523 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4524 mCurrentCookedState.stylusIdBits.markBit(id);
4525 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4526 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4527 mCurrentCookedState.fingerIdBits.markBit(id);
4528 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4529 mCurrentCookedState.mouseIdBits.markBit(id);
4530 }
4531 }
4532 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4533 !idBits.isEmpty(); ) {
4534 uint32_t id = idBits.clearFirstMarkedBit();
4535 const RawPointerData::Pointer& pointer =
4536 mCurrentRawState.rawPointerData.pointerForId(id);
4537 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4538 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4539 mCurrentCookedState.stylusIdBits.markBit(id);
4540 }
4541 }
4542
4543 // Stylus takes precedence over all tools, then mouse, then finger.
4544 PointerUsage pointerUsage = mPointerUsage;
4545 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4546 mCurrentCookedState.mouseIdBits.clear();
4547 mCurrentCookedState.fingerIdBits.clear();
4548 pointerUsage = POINTER_USAGE_STYLUS;
4549 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4550 mCurrentCookedState.fingerIdBits.clear();
4551 pointerUsage = POINTER_USAGE_MOUSE;
4552 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4553 isPointerDown(mCurrentRawState.buttonState)) {
4554 pointerUsage = POINTER_USAGE_GESTURES;
4555 }
4556
4557 dispatchPointerUsage(when, policyFlags, pointerUsage);
4558 } else {
4559 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004560 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004561 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4562 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4563
4564 mPointerController->setButtonState(mCurrentRawState.buttonState);
4565 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4566 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004567 mCurrentCookedState.cookedPointerData.touchingIdBits,
4568 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004569 }
4570
Michael Wright8e812822015-06-22 16:18:21 +01004571 if (!mCurrentMotionAborted) {
4572 dispatchButtonRelease(when, policyFlags);
4573 dispatchHoverExit(when, policyFlags);
4574 dispatchTouches(when, policyFlags);
4575 dispatchHoverEnterAndMove(when, policyFlags);
4576 dispatchButtonPress(when, policyFlags);
4577 }
4578
4579 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4580 mCurrentMotionAborted = false;
4581 }
Michael Wright842500e2015-03-13 17:32:02 -07004582 }
4583
4584 // Synthesize key up from raw buttons if needed.
4585 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004586 mViewport.displayId, policyFlags,
4587 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004588
4589 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004590 mCurrentRawState.rawVScroll = 0;
4591 mCurrentRawState.rawHScroll = 0;
4592
4593 // Copy current touch to last touch in preparation for the next cycle.
4594 mLastRawState.copyFrom(mCurrentRawState);
4595 mLastCookedState.copyFrom(mCurrentCookedState);
4596}
4597
4598void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004599 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004600 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4601 }
4602}
4603
4604void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004605 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4606 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004607
Michael Wright53dca3a2015-04-23 17:39:53 +01004608 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4609 float pressure = mExternalStylusState.pressure;
4610 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4611 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4612 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4613 }
4614 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4615 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4616
4617 PointerProperties& properties =
4618 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004619 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4620 properties.toolType = mExternalStylusState.toolType;
4621 }
4622 }
4623}
4624
4625bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4626 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4627 return false;
4628 }
4629
4630 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4631 && state.rawPointerData.pointerCount != 0;
4632 if (initialDown) {
4633 if (mExternalStylusState.pressure != 0.0f) {
4634#if DEBUG_STYLUS_FUSION
4635 ALOGD("Have both stylus and touch data, beginning fusion");
4636#endif
4637 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4638 } else if (timeout) {
4639#if DEBUG_STYLUS_FUSION
4640 ALOGD("Timeout expired, assuming touch is not a stylus.");
4641#endif
4642 resetExternalStylus();
4643 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004644 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4645 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004646 }
4647#if DEBUG_STYLUS_FUSION
4648 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004649 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004650#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004651 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004652 return true;
4653 }
4654 }
4655
4656 // Check if the stylus pointer has gone up.
4657 if (mExternalStylusId != -1 &&
4658 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4659#if DEBUG_STYLUS_FUSION
4660 ALOGD("Stylus pointer is going up");
4661#endif
4662 mExternalStylusId = -1;
4663 }
4664
4665 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666}
4667
4668void TouchInputMapper::timeoutExpired(nsecs_t when) {
4669 if (mDeviceMode == DEVICE_MODE_POINTER) {
4670 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4671 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4672 }
Michael Wright842500e2015-03-13 17:32:02 -07004673 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004674 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004675 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004676 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4677 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004678 }
4679 }
4680}
4681
4682void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004683 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004684 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004685 // We're either in the middle of a fused stream of data or we're waiting on data before
4686 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4687 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004688 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004689 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 }
4691}
4692
4693bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4694 // Check for release of a virtual key.
4695 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004696 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004697 // Pointer went up while virtual key was down.
4698 mCurrentVirtualKey.down = false;
4699 if (!mCurrentVirtualKey.ignored) {
4700#if DEBUG_VIRTUAL_KEYS
4701 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4702 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4703#endif
4704 dispatchVirtualKey(when, policyFlags,
4705 AKEY_EVENT_ACTION_UP,
4706 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4707 }
4708 return true;
4709 }
4710
Michael Wright842500e2015-03-13 17:32:02 -07004711 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4712 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4713 const RawPointerData::Pointer& pointer =
4714 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004715 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4716 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4717 // Pointer is still within the space of the virtual key.
4718 return true;
4719 }
4720 }
4721
4722 // Pointer left virtual key area or another pointer also went down.
4723 // Send key cancellation but do not consume the touch yet.
4724 // This is useful when the user swipes through from the virtual key area
4725 // into the main display surface.
4726 mCurrentVirtualKey.down = false;
4727 if (!mCurrentVirtualKey.ignored) {
4728#if DEBUG_VIRTUAL_KEYS
4729 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4730 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4731#endif
4732 dispatchVirtualKey(when, policyFlags,
4733 AKEY_EVENT_ACTION_UP,
4734 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4735 | AKEY_EVENT_FLAG_CANCELED);
4736 }
4737 }
4738
Michael Wright842500e2015-03-13 17:32:02 -07004739 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4740 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004742 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4743 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4745 // If exactly one pointer went down, check for virtual key hit.
4746 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004747 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4749 if (virtualKey) {
4750 mCurrentVirtualKey.down = true;
4751 mCurrentVirtualKey.downTime = when;
4752 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4753 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4754 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4755 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4756
4757 if (!mCurrentVirtualKey.ignored) {
4758#if DEBUG_VIRTUAL_KEYS
4759 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4760 mCurrentVirtualKey.keyCode,
4761 mCurrentVirtualKey.scanCode);
4762#endif
4763 dispatchVirtualKey(when, policyFlags,
4764 AKEY_EVENT_ACTION_DOWN,
4765 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4766 }
4767 }
4768 }
4769 return true;
4770 }
4771 }
4772
4773 // Disable all virtual key touches that happen within a short time interval of the
4774 // most recent touch within the screen area. The idea is to filter out stray
4775 // virtual key presses when interacting with the touch screen.
4776 //
4777 // Problems we're trying to solve:
4778 //
4779 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4780 // virtual key area that is implemented by a separate touch panel and accidentally
4781 // triggers a virtual key.
4782 //
4783 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4784 // area and accidentally triggers a virtual key. This often happens when virtual keys
4785 // are layed out below the screen near to where the on screen keyboard's space bar
4786 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004787 if (mConfig.virtualKeyQuietTime > 0 &&
4788 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4790 }
4791 return false;
4792}
4793
4794void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4795 int32_t keyEventAction, int32_t keyEventFlags) {
4796 int32_t keyCode = mCurrentVirtualKey.keyCode;
4797 int32_t scanCode = mCurrentVirtualKey.scanCode;
4798 nsecs_t downTime = mCurrentVirtualKey.downTime;
4799 int32_t metaState = mContext->getGlobalMetaState();
4800 policyFlags |= POLICY_FLAG_VIRTUAL;
4801
Prabir Pradhan42611e02018-11-27 14:04:02 -08004802 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4803 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004804 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 getListener()->notifyKey(&args);
4806}
4807
Michael Wright8e812822015-06-22 16:18:21 +01004808void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4809 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4810 if (!currentIdBits.isEmpty()) {
4811 int32_t metaState = getContext()->getGlobalMetaState();
4812 int32_t buttonState = mCurrentCookedState.buttonState;
4813 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4814 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4815 mCurrentCookedState.cookedPointerData.pointerProperties,
4816 mCurrentCookedState.cookedPointerData.pointerCoords,
4817 mCurrentCookedState.cookedPointerData.idToIndex,
4818 currentIdBits, -1,
4819 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4820 mCurrentMotionAborted = true;
4821 }
4822}
4823
Michael Wrightd02c5b62014-02-10 15:10:22 -08004824void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004825 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4826 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004828 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004829
4830 if (currentIdBits == lastIdBits) {
4831 if (!currentIdBits.isEmpty()) {
4832 // No pointer id changes so this is a move event.
4833 // The listener takes care of batching moves so we don't have to deal with that here.
4834 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004835 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004837 mCurrentCookedState.cookedPointerData.pointerProperties,
4838 mCurrentCookedState.cookedPointerData.pointerCoords,
4839 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 currentIdBits, -1,
4841 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4842 }
4843 } else {
4844 // There may be pointers going up and pointers going down and pointers moving
4845 // all at the same time.
4846 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4847 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4848 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4849 BitSet32 dispatchedIdBits(lastIdBits.value);
4850
4851 // Update last coordinates of pointers that have moved so that we observe the new
4852 // pointer positions at the same time as other pointers that have just gone up.
4853 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004854 mCurrentCookedState.cookedPointerData.pointerProperties,
4855 mCurrentCookedState.cookedPointerData.pointerCoords,
4856 mCurrentCookedState.cookedPointerData.idToIndex,
4857 mLastCookedState.cookedPointerData.pointerProperties,
4858 mLastCookedState.cookedPointerData.pointerCoords,
4859 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004860 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004861 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 moveNeeded = true;
4863 }
4864
4865 // Dispatch pointer up events.
4866 while (!upIdBits.isEmpty()) {
4867 uint32_t upId = upIdBits.clearFirstMarkedBit();
4868
4869 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004870 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004871 mLastCookedState.cookedPointerData.pointerProperties,
4872 mLastCookedState.cookedPointerData.pointerCoords,
4873 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004874 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 dispatchedIdBits.clearBit(upId);
4876 }
4877
4878 // Dispatch move events if any of the remaining pointers moved from their old locations.
4879 // Although applications receive new locations as part of individual pointer up
4880 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004881 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4883 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004884 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004885 mCurrentCookedState.cookedPointerData.pointerProperties,
4886 mCurrentCookedState.cookedPointerData.pointerCoords,
4887 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004888 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 }
4890
4891 // Dispatch pointer down events using the new pointer locations.
4892 while (!downIdBits.isEmpty()) {
4893 uint32_t downId = downIdBits.clearFirstMarkedBit();
4894 dispatchedIdBits.markBit(downId);
4895
4896 if (dispatchedIdBits.count() == 1) {
4897 // First pointer is going down. Set down time.
4898 mDownTime = when;
4899 }
4900
4901 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004902 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004903 mCurrentCookedState.cookedPointerData.pointerProperties,
4904 mCurrentCookedState.cookedPointerData.pointerCoords,
4905 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004906 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004907 }
4908 }
4909}
4910
4911void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4912 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004913 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4914 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 int32_t metaState = getContext()->getGlobalMetaState();
4916 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004917 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004918 mLastCookedState.cookedPointerData.pointerProperties,
4919 mLastCookedState.cookedPointerData.pointerCoords,
4920 mLastCookedState.cookedPointerData.idToIndex,
4921 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4923 mSentHoverEnter = false;
4924 }
4925}
4926
4927void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004928 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4929 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 int32_t metaState = getContext()->getGlobalMetaState();
4931 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004932 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004933 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004934 mCurrentCookedState.cookedPointerData.pointerProperties,
4935 mCurrentCookedState.cookedPointerData.pointerCoords,
4936 mCurrentCookedState.cookedPointerData.idToIndex,
4937 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4939 mSentHoverEnter = true;
4940 }
4941
4942 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004943 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004944 mCurrentRawState.buttonState, 0,
4945 mCurrentCookedState.cookedPointerData.pointerProperties,
4946 mCurrentCookedState.cookedPointerData.pointerCoords,
4947 mCurrentCookedState.cookedPointerData.idToIndex,
4948 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004949 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4950 }
4951}
4952
Michael Wright7b159c92015-05-14 14:48:03 +01004953void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4954 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4955 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4956 const int32_t metaState = getContext()->getGlobalMetaState();
4957 int32_t buttonState = mLastCookedState.buttonState;
4958 while (!releasedButtons.isEmpty()) {
4959 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4960 buttonState &= ~actionButton;
4961 dispatchMotion(when, policyFlags, mSource,
4962 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4963 0, metaState, buttonState, 0,
4964 mCurrentCookedState.cookedPointerData.pointerProperties,
4965 mCurrentCookedState.cookedPointerData.pointerCoords,
4966 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4967 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4968 }
4969}
4970
4971void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4972 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4973 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4974 const int32_t metaState = getContext()->getGlobalMetaState();
4975 int32_t buttonState = mLastCookedState.buttonState;
4976 while (!pressedButtons.isEmpty()) {
4977 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4978 buttonState |= actionButton;
4979 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4980 0, metaState, buttonState, 0,
4981 mCurrentCookedState.cookedPointerData.pointerProperties,
4982 mCurrentCookedState.cookedPointerData.pointerCoords,
4983 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4984 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4985 }
4986}
4987
4988const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4989 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4990 return cookedPointerData.touchingIdBits;
4991 }
4992 return cookedPointerData.hoveringIdBits;
4993}
4994
Michael Wrightd02c5b62014-02-10 15:10:22 -08004995void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004996 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004997
Michael Wright842500e2015-03-13 17:32:02 -07004998 mCurrentCookedState.cookedPointerData.clear();
4999 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
5000 mCurrentCookedState.cookedPointerData.hoveringIdBits =
5001 mCurrentRawState.rawPointerData.hoveringIdBits;
5002 mCurrentCookedState.cookedPointerData.touchingIdBits =
5003 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004
Michael Wright7b159c92015-05-14 14:48:03 +01005005 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
5006 mCurrentCookedState.buttonState = 0;
5007 } else {
5008 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
5009 }
5010
Michael Wrightd02c5b62014-02-10 15:10:22 -08005011 // Walk through the the active pointers and map device coordinates onto
5012 // surface coordinates and adjust for display orientation.
5013 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07005014 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015
5016 // Size
5017 float touchMajor, touchMinor, toolMajor, toolMinor, size;
5018 switch (mCalibration.sizeCalibration) {
5019 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
5020 case Calibration::SIZE_CALIBRATION_DIAMETER:
5021 case Calibration::SIZE_CALIBRATION_BOX:
5022 case Calibration::SIZE_CALIBRATION_AREA:
5023 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
5024 touchMajor = in.touchMajor;
5025 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
5026 toolMajor = in.toolMajor;
5027 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
5028 size = mRawPointerAxes.touchMinor.valid
5029 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5030 } else if (mRawPointerAxes.touchMajor.valid) {
5031 toolMajor = touchMajor = in.touchMajor;
5032 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
5033 ? in.touchMinor : in.touchMajor;
5034 size = mRawPointerAxes.touchMinor.valid
5035 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5036 } else if (mRawPointerAxes.toolMajor.valid) {
5037 touchMajor = toolMajor = in.toolMajor;
5038 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5039 ? in.toolMinor : in.toolMajor;
5040 size = mRawPointerAxes.toolMinor.valid
5041 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5042 } else {
5043 ALOG_ASSERT(false, "No touch or tool axes. "
5044 "Size calibration should have been resolved to NONE.");
5045 touchMajor = 0;
5046 touchMinor = 0;
5047 toolMajor = 0;
5048 toolMinor = 0;
5049 size = 0;
5050 }
5051
5052 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005053 uint32_t touchingCount =
5054 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005055 if (touchingCount > 1) {
5056 touchMajor /= touchingCount;
5057 touchMinor /= touchingCount;
5058 toolMajor /= touchingCount;
5059 toolMinor /= touchingCount;
5060 size /= touchingCount;
5061 }
5062 }
5063
5064 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5065 touchMajor *= mGeometricScale;
5066 touchMinor *= mGeometricScale;
5067 toolMajor *= mGeometricScale;
5068 toolMinor *= mGeometricScale;
5069 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5070 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5071 touchMinor = touchMajor;
5072 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5073 toolMinor = toolMajor;
5074 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5075 touchMinor = touchMajor;
5076 toolMinor = toolMajor;
5077 }
5078
5079 mCalibration.applySizeScaleAndBias(&touchMajor);
5080 mCalibration.applySizeScaleAndBias(&touchMinor);
5081 mCalibration.applySizeScaleAndBias(&toolMajor);
5082 mCalibration.applySizeScaleAndBias(&toolMinor);
5083 size *= mSizeScale;
5084 break;
5085 default:
5086 touchMajor = 0;
5087 touchMinor = 0;
5088 toolMajor = 0;
5089 toolMinor = 0;
5090 size = 0;
5091 break;
5092 }
5093
5094 // Pressure
5095 float pressure;
5096 switch (mCalibration.pressureCalibration) {
5097 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5098 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5099 pressure = in.pressure * mPressureScale;
5100 break;
5101 default:
5102 pressure = in.isHovering ? 0 : 1;
5103 break;
5104 }
5105
5106 // Tilt and Orientation
5107 float tilt;
5108 float orientation;
5109 if (mHaveTilt) {
5110 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5111 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5112 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5113 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5114 } else {
5115 tilt = 0;
5116
5117 switch (mCalibration.orientationCalibration) {
5118 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5119 orientation = in.orientation * mOrientationScale;
5120 break;
5121 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5122 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5123 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5124 if (c1 != 0 || c2 != 0) {
5125 orientation = atan2f(c1, c2) * 0.5f;
5126 float confidence = hypotf(c1, c2);
5127 float scale = 1.0f + confidence / 16.0f;
5128 touchMajor *= scale;
5129 touchMinor /= scale;
5130 toolMajor *= scale;
5131 toolMinor /= scale;
5132 } else {
5133 orientation = 0;
5134 }
5135 break;
5136 }
5137 default:
5138 orientation = 0;
5139 }
5140 }
5141
5142 // Distance
5143 float distance;
5144 switch (mCalibration.distanceCalibration) {
5145 case Calibration::DISTANCE_CALIBRATION_SCALED:
5146 distance = in.distance * mDistanceScale;
5147 break;
5148 default:
5149 distance = 0;
5150 }
5151
5152 // Coverage
5153 int32_t rawLeft, rawTop, rawRight, rawBottom;
5154 switch (mCalibration.coverageCalibration) {
5155 case Calibration::COVERAGE_CALIBRATION_BOX:
5156 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5157 rawRight = in.toolMinor & 0x0000ffff;
5158 rawBottom = in.toolMajor & 0x0000ffff;
5159 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5160 break;
5161 default:
5162 rawLeft = rawTop = rawRight = rawBottom = 0;
5163 break;
5164 }
5165
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005166 // Adjust X,Y coords for device calibration
5167 // TODO: Adjust coverage coords?
5168 float xTransformed = in.x, yTransformed = in.y;
5169 mAffineTransform.applyTo(xTransformed, yTransformed);
5170
5171 // Adjust X, Y, and coverage coords for surface orientation.
5172 float x, y;
5173 float left, top, right, bottom;
5174
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 switch (mSurfaceOrientation) {
5176 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005177 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5178 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005179 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5180 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5181 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5182 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5183 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005184 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5186 }
5187 break;
5188 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005189 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005190 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005191 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5192 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005193 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5194 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5195 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005196 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005197 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5198 }
5199 break;
5200 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005201 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005202 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005203 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5204 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5206 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5207 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005208 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005209 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5210 }
5211 break;
5212 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005213 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5214 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5216 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5217 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5218 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5219 break;
5220 }
5221
5222 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005223 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005224 out.clear();
5225 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5226 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5227 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5228 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5229 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5230 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5231 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5232 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5233 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5234 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5235 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5236 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5237 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5238 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5239 } else {
5240 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5241 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5242 }
5243
5244 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005245 PointerProperties& properties =
5246 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005247 uint32_t id = in.id;
5248 properties.clear();
5249 properties.id = id;
5250 properties.toolType = in.toolType;
5251
5252 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005253 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005254 }
5255}
5256
5257void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5258 PointerUsage pointerUsage) {
5259 if (pointerUsage != mPointerUsage) {
5260 abortPointerUsage(when, policyFlags);
5261 mPointerUsage = pointerUsage;
5262 }
5263
5264 switch (mPointerUsage) {
5265 case POINTER_USAGE_GESTURES:
5266 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5267 break;
5268 case POINTER_USAGE_STYLUS:
5269 dispatchPointerStylus(when, policyFlags);
5270 break;
5271 case POINTER_USAGE_MOUSE:
5272 dispatchPointerMouse(when, policyFlags);
5273 break;
5274 default:
5275 break;
5276 }
5277}
5278
5279void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5280 switch (mPointerUsage) {
5281 case POINTER_USAGE_GESTURES:
5282 abortPointerGestures(when, policyFlags);
5283 break;
5284 case POINTER_USAGE_STYLUS:
5285 abortPointerStylus(when, policyFlags);
5286 break;
5287 case POINTER_USAGE_MOUSE:
5288 abortPointerMouse(when, policyFlags);
5289 break;
5290 default:
5291 break;
5292 }
5293
5294 mPointerUsage = POINTER_USAGE_NONE;
5295}
5296
5297void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5298 bool isTimeout) {
5299 // Update current gesture coordinates.
5300 bool cancelPreviousGesture, finishPreviousGesture;
5301 bool sendEvents = preparePointerGestures(when,
5302 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5303 if (!sendEvents) {
5304 return;
5305 }
5306 if (finishPreviousGesture) {
5307 cancelPreviousGesture = false;
5308 }
5309
5310 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005311 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5312 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 if (finishPreviousGesture || cancelPreviousGesture) {
5314 mPointerController->clearSpots();
5315 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005316
5317 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5318 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5319 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005320 mPointerGesture.currentGestureIdBits,
5321 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005322 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 } else {
5324 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5325 }
5326
5327 // Show or hide the pointer if needed.
5328 switch (mPointerGesture.currentGestureMode) {
5329 case PointerGesture::NEUTRAL:
5330 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005331 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5332 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005333 // Remind the user of where the pointer is after finishing a gesture with spots.
5334 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5335 }
5336 break;
5337 case PointerGesture::TAP:
5338 case PointerGesture::TAP_DRAG:
5339 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5340 case PointerGesture::HOVER:
5341 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005342 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 // Unfade the pointer when the current gesture manipulates the
5344 // area directly under the pointer.
5345 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5346 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 case PointerGesture::FREEFORM:
5348 // Fade the pointer when the current gesture manipulates a different
5349 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005350 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5352 } else {
5353 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5354 }
5355 break;
5356 }
5357
5358 // Send events!
5359 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005360 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361
5362 // Update last coordinates of pointers that have moved so that we observe the new
5363 // pointer positions at the same time as other pointers that have just gone up.
5364 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5365 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5366 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5367 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5368 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5369 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5370 bool moveNeeded = false;
5371 if (down && !cancelPreviousGesture && !finishPreviousGesture
5372 && !mPointerGesture.lastGestureIdBits.isEmpty()
5373 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5374 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5375 & mPointerGesture.lastGestureIdBits.value);
5376 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5377 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5378 mPointerGesture.lastGestureProperties,
5379 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5380 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005381 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005382 moveNeeded = true;
5383 }
5384 }
5385
5386 // Send motion events for all pointers that went up or were canceled.
5387 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5388 if (!dispatchedGestureIdBits.isEmpty()) {
5389 if (cancelPreviousGesture) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005390 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5391 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5392 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5393 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5394 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
5396 dispatchedGestureIdBits.clear();
5397 } else {
5398 BitSet32 upGestureIdBits;
5399 if (finishPreviousGesture) {
5400 upGestureIdBits = dispatchedGestureIdBits;
5401 } else {
5402 upGestureIdBits.value = dispatchedGestureIdBits.value
5403 & ~mPointerGesture.currentGestureIdBits.value;
5404 }
5405 while (!upGestureIdBits.isEmpty()) {
5406 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5407
5408 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005409 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5411 mPointerGesture.lastGestureProperties,
5412 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5413 dispatchedGestureIdBits, id,
5414 0, 0, mPointerGesture.downTime);
5415
5416 dispatchedGestureIdBits.clearBit(id);
5417 }
5418 }
5419 }
5420
5421 // Send motion events for all pointers that moved.
5422 if (moveNeeded) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005423 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5424 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5425 mPointerGesture.currentGestureProperties,
5426 mPointerGesture.currentGestureCoords,
5427 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5428 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 }
5430
5431 // Send motion events for all pointers that went down.
5432 if (down) {
5433 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5434 & ~dispatchedGestureIdBits.value);
5435 while (!downGestureIdBits.isEmpty()) {
5436 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5437 dispatchedGestureIdBits.markBit(id);
5438
5439 if (dispatchedGestureIdBits.count() == 1) {
5440 mPointerGesture.downTime = when;
5441 }
5442
5443 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005444 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 mPointerGesture.currentGestureProperties,
5446 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5447 dispatchedGestureIdBits, id,
5448 0, 0, mPointerGesture.downTime);
5449 }
5450 }
5451
5452 // Send motion events for hover.
5453 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005454 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5455 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5456 mPointerGesture.currentGestureProperties,
5457 mPointerGesture.currentGestureCoords,
5458 mPointerGesture.currentGestureIdToIndex,
5459 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 } else if (dispatchedGestureIdBits.isEmpty()
5461 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5462 // Synthesize a hover move event after all pointers go up to indicate that
5463 // the pointer is hovering again even if the user is not currently touching
5464 // the touch pad. This ensures that a view will receive a fresh hover enter
5465 // event after a tap.
5466 float x, y;
5467 mPointerController->getPosition(&x, &y);
5468
5469 PointerProperties pointerProperties;
5470 pointerProperties.clear();
5471 pointerProperties.id = 0;
5472 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5473
5474 PointerCoords pointerCoords;
5475 pointerCoords.clear();
5476 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5477 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5478
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005479 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005480 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5481 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5482 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005483 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
5484 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 getListener()->notifyMotion(&args);
5486 }
5487
5488 // Update state.
5489 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5490 if (!down) {
5491 mPointerGesture.lastGestureIdBits.clear();
5492 } else {
5493 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5494 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5495 uint32_t id = idBits.clearFirstMarkedBit();
5496 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5497 mPointerGesture.lastGestureProperties[index].copyFrom(
5498 mPointerGesture.currentGestureProperties[index]);
5499 mPointerGesture.lastGestureCoords[index].copyFrom(
5500 mPointerGesture.currentGestureCoords[index]);
5501 mPointerGesture.lastGestureIdToIndex[id] = index;
5502 }
5503 }
5504}
5505
5506void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5507 // Cancel previously dispatches pointers.
5508 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5509 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005510 int32_t buttonState = mCurrentRawState.buttonState;
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005511 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5512 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5513 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5514 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5515 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 }
5517
5518 // Reset the current pointer gesture.
5519 mPointerGesture.reset();
5520 mPointerVelocityControl.reset();
5521
5522 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005523 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5525 mPointerController->clearSpots();
5526 }
5527}
5528
5529bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5530 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5531 *outCancelPreviousGesture = false;
5532 *outFinishPreviousGesture = false;
5533
5534 // Handle TAP timeout.
5535 if (isTimeout) {
5536#if DEBUG_GESTURES
5537 ALOGD("Gestures: Processing timeout");
5538#endif
5539
5540 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5541 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5542 // The tap/drag timeout has not yet expired.
5543 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5544 + mConfig.pointerGestureTapDragInterval);
5545 } else {
5546 // The tap is finished.
5547#if DEBUG_GESTURES
5548 ALOGD("Gestures: TAP finished");
5549#endif
5550 *outFinishPreviousGesture = true;
5551
5552 mPointerGesture.activeGestureId = -1;
5553 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5554 mPointerGesture.currentGestureIdBits.clear();
5555
5556 mPointerVelocityControl.reset();
5557 return true;
5558 }
5559 }
5560
5561 // We did not handle this timeout.
5562 return false;
5563 }
5564
Michael Wright842500e2015-03-13 17:32:02 -07005565 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5566 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567
5568 // Update the velocity tracker.
5569 {
5570 VelocityTracker::Position positions[MAX_POINTERS];
5571 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005572 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005573 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005574 const RawPointerData::Pointer& pointer =
5575 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 positions[count].x = pointer.x * mPointerXMovementScale;
5577 positions[count].y = pointer.y * mPointerYMovementScale;
5578 }
5579 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005580 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 }
5582
5583 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5584 // to NEUTRAL, then we should not generate tap event.
5585 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5586 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5587 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5588 mPointerGesture.resetTap();
5589 }
5590
5591 // Pick a new active touch id if needed.
5592 // Choose an arbitrary pointer that just went down, if there is one.
5593 // Otherwise choose an arbitrary remaining pointer.
5594 // This guarantees we always have an active touch id when there is at least one pointer.
5595 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5597 int32_t activeTouchId = lastActiveTouchId;
5598 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005599 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005601 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005602 mPointerGesture.firstTouchTime = when;
5603 }
Michael Wright842500e2015-03-13 17:32:02 -07005604 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005605 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005607 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005608 } else {
5609 activeTouchId = mPointerGesture.activeTouchId = -1;
5610 }
5611 }
5612
5613 // Determine whether we are in quiet time.
5614 bool isQuietTime = false;
5615 if (activeTouchId < 0) {
5616 mPointerGesture.resetQuietTime();
5617 } else {
5618 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5619 if (!isQuietTime) {
5620 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5621 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5622 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5623 && currentFingerCount < 2) {
5624 // Enter quiet time when exiting swipe or freeform state.
5625 // This is to prevent accidentally entering the hover state and flinging the
5626 // pointer when finishing a swipe and there is still one pointer left onscreen.
5627 isQuietTime = true;
5628 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5629 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005630 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005631 // Enter quiet time when releasing the button and there are still two or more
5632 // fingers down. This may indicate that one finger was used to press the button
5633 // but it has not gone up yet.
5634 isQuietTime = true;
5635 }
5636 if (isQuietTime) {
5637 mPointerGesture.quietTime = when;
5638 }
5639 }
5640 }
5641
5642 // Switch states based on button and pointer state.
5643 if (isQuietTime) {
5644 // Case 1: Quiet time. (QUIET)
5645#if DEBUG_GESTURES
5646 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5647 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5648#endif
5649 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5650 *outFinishPreviousGesture = true;
5651 }
5652
5653 mPointerGesture.activeGestureId = -1;
5654 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5655 mPointerGesture.currentGestureIdBits.clear();
5656
5657 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005658 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5660 // The pointer follows the active touch point.
5661 // Emit DOWN, MOVE, UP events at the pointer location.
5662 //
5663 // Only the active touch matters; other fingers are ignored. This policy helps
5664 // to handle the case where the user places a second finger on the touch pad
5665 // to apply the necessary force to depress an integrated button below the surface.
5666 // We don't want the second finger to be delivered to applications.
5667 //
5668 // For this to work well, we need to make sure to track the pointer that is really
5669 // active. If the user first puts one finger down to click then adds another
5670 // finger to drag then the active pointer should switch to the finger that is
5671 // being dragged.
5672#if DEBUG_GESTURES
5673 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5674 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5675#endif
5676 // Reset state when just starting.
5677 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5678 *outFinishPreviousGesture = true;
5679 mPointerGesture.activeGestureId = 0;
5680 }
5681
5682 // Switch pointers if needed.
5683 // Find the fastest pointer and follow it.
5684 if (activeTouchId >= 0 && currentFingerCount > 1) {
5685 int32_t bestId = -1;
5686 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005687 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005688 uint32_t id = idBits.clearFirstMarkedBit();
5689 float vx, vy;
5690 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5691 float speed = hypotf(vx, vy);
5692 if (speed > bestSpeed) {
5693 bestId = id;
5694 bestSpeed = speed;
5695 }
5696 }
5697 }
5698 if (bestId >= 0 && bestId != activeTouchId) {
5699 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005700#if DEBUG_GESTURES
5701 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5702 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5703#endif
5704 }
5705 }
5706
Jun Mukaifa1706a2015-12-03 01:14:46 -08005707 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005708 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005709 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005710 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005711 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005712 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005713 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5714 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005715
5716 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5717 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5718
5719 // Move the pointer using a relative motion.
5720 // When using spots, the click will occur at the position of the anchor
5721 // spot and all other spots will move there.
5722 mPointerController->move(deltaX, deltaY);
5723 } else {
5724 mPointerVelocityControl.reset();
5725 }
5726
5727 float x, y;
5728 mPointerController->getPosition(&x, &y);
5729
5730 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5731 mPointerGesture.currentGestureIdBits.clear();
5732 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5733 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5734 mPointerGesture.currentGestureProperties[0].clear();
5735 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5736 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5737 mPointerGesture.currentGestureCoords[0].clear();
5738 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5739 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5740 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5741 } else if (currentFingerCount == 0) {
5742 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5743 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5744 *outFinishPreviousGesture = true;
5745 }
5746
5747 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5748 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5749 bool tapped = false;
5750 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5751 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5752 && lastFingerCount == 1) {
5753 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5754 float x, y;
5755 mPointerController->getPosition(&x, &y);
5756 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5757 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5758#if DEBUG_GESTURES
5759 ALOGD("Gestures: TAP");
5760#endif
5761
5762 mPointerGesture.tapUpTime = when;
5763 getContext()->requestTimeoutAtTime(when
5764 + mConfig.pointerGestureTapDragInterval);
5765
5766 mPointerGesture.activeGestureId = 0;
5767 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5768 mPointerGesture.currentGestureIdBits.clear();
5769 mPointerGesture.currentGestureIdBits.markBit(
5770 mPointerGesture.activeGestureId);
5771 mPointerGesture.currentGestureIdToIndex[
5772 mPointerGesture.activeGestureId] = 0;
5773 mPointerGesture.currentGestureProperties[0].clear();
5774 mPointerGesture.currentGestureProperties[0].id =
5775 mPointerGesture.activeGestureId;
5776 mPointerGesture.currentGestureProperties[0].toolType =
5777 AMOTION_EVENT_TOOL_TYPE_FINGER;
5778 mPointerGesture.currentGestureCoords[0].clear();
5779 mPointerGesture.currentGestureCoords[0].setAxisValue(
5780 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5781 mPointerGesture.currentGestureCoords[0].setAxisValue(
5782 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5783 mPointerGesture.currentGestureCoords[0].setAxisValue(
5784 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5785
5786 tapped = true;
5787 } else {
5788#if DEBUG_GESTURES
5789 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5790 x - mPointerGesture.tapX,
5791 y - mPointerGesture.tapY);
5792#endif
5793 }
5794 } else {
5795#if DEBUG_GESTURES
5796 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5797 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5798 (when - mPointerGesture.tapDownTime) * 0.000001f);
5799 } else {
5800 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5801 }
5802#endif
5803 }
5804 }
5805
5806 mPointerVelocityControl.reset();
5807
5808 if (!tapped) {
5809#if DEBUG_GESTURES
5810 ALOGD("Gestures: NEUTRAL");
5811#endif
5812 mPointerGesture.activeGestureId = -1;
5813 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5814 mPointerGesture.currentGestureIdBits.clear();
5815 }
5816 } else if (currentFingerCount == 1) {
5817 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5818 // The pointer follows the active touch point.
5819 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5820 // When in TAP_DRAG, emit MOVE events at the pointer location.
5821 ALOG_ASSERT(activeTouchId >= 0);
5822
5823 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5824 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5825 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5826 float x, y;
5827 mPointerController->getPosition(&x, &y);
5828 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5829 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5830 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5831 } else {
5832#if DEBUG_GESTURES
5833 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5834 x - mPointerGesture.tapX,
5835 y - mPointerGesture.tapY);
5836#endif
5837 }
5838 } else {
5839#if DEBUG_GESTURES
5840 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5841 (when - mPointerGesture.tapUpTime) * 0.000001f);
5842#endif
5843 }
5844 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5845 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5846 }
5847
Jun Mukaifa1706a2015-12-03 01:14:46 -08005848 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005849 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005850 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005851 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005852 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005853 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005854 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5855 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856
5857 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5858 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5859
5860 // Move the pointer using a relative motion.
5861 // When using spots, the hover or drag will occur at the position of the anchor spot.
5862 mPointerController->move(deltaX, deltaY);
5863 } else {
5864 mPointerVelocityControl.reset();
5865 }
5866
5867 bool down;
5868 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5869#if DEBUG_GESTURES
5870 ALOGD("Gestures: TAP_DRAG");
5871#endif
5872 down = true;
5873 } else {
5874#if DEBUG_GESTURES
5875 ALOGD("Gestures: HOVER");
5876#endif
5877 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5878 *outFinishPreviousGesture = true;
5879 }
5880 mPointerGesture.activeGestureId = 0;
5881 down = false;
5882 }
5883
5884 float x, y;
5885 mPointerController->getPosition(&x, &y);
5886
5887 mPointerGesture.currentGestureIdBits.clear();
5888 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5889 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5890 mPointerGesture.currentGestureProperties[0].clear();
5891 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5892 mPointerGesture.currentGestureProperties[0].toolType =
5893 AMOTION_EVENT_TOOL_TYPE_FINGER;
5894 mPointerGesture.currentGestureCoords[0].clear();
5895 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5896 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5897 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5898 down ? 1.0f : 0.0f);
5899
5900 if (lastFingerCount == 0 && currentFingerCount != 0) {
5901 mPointerGesture.resetTap();
5902 mPointerGesture.tapDownTime = when;
5903 mPointerGesture.tapX = x;
5904 mPointerGesture.tapY = y;
5905 }
5906 } else {
5907 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5908 // We need to provide feedback for each finger that goes down so we cannot wait
5909 // for the fingers to move before deciding what to do.
5910 //
5911 // The ambiguous case is deciding what to do when there are two fingers down but they
5912 // have not moved enough to determine whether they are part of a drag or part of a
5913 // freeform gesture, or just a press or long-press at the pointer location.
5914 //
5915 // When there are two fingers we start with the PRESS hypothesis and we generate a
5916 // down at the pointer location.
5917 //
5918 // When the two fingers move enough or when additional fingers are added, we make
5919 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5920 ALOG_ASSERT(activeTouchId >= 0);
5921
5922 bool settled = when >= mPointerGesture.firstTouchTime
5923 + mConfig.pointerGestureMultitouchSettleInterval;
5924 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5925 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5926 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5927 *outFinishPreviousGesture = true;
5928 } else if (!settled && currentFingerCount > lastFingerCount) {
5929 // Additional pointers have gone down but not yet settled.
5930 // Reset the gesture.
5931#if DEBUG_GESTURES
5932 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5933 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5934 + mConfig.pointerGestureMultitouchSettleInterval - when)
5935 * 0.000001f);
5936#endif
5937 *outCancelPreviousGesture = true;
5938 } else {
5939 // Continue previous gesture.
5940 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5941 }
5942
5943 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5944 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5945 mPointerGesture.activeGestureId = 0;
5946 mPointerGesture.referenceIdBits.clear();
5947 mPointerVelocityControl.reset();
5948
5949 // Use the centroid and pointer location as the reference points for the gesture.
5950#if DEBUG_GESTURES
5951 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5952 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5953 + mConfig.pointerGestureMultitouchSettleInterval - when)
5954 * 0.000001f);
5955#endif
Michael Wright842500e2015-03-13 17:32:02 -07005956 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957 &mPointerGesture.referenceTouchX,
5958 &mPointerGesture.referenceTouchY);
5959 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5960 &mPointerGesture.referenceGestureY);
5961 }
5962
5963 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005964 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5966 uint32_t id = idBits.clearFirstMarkedBit();
5967 mPointerGesture.referenceDeltas[id].dx = 0;
5968 mPointerGesture.referenceDeltas[id].dy = 0;
5969 }
Michael Wright842500e2015-03-13 17:32:02 -07005970 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971
5972 // Add delta for all fingers and calculate a common movement delta.
5973 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005974 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5975 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5977 bool first = (idBits == commonIdBits);
5978 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005979 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5980 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5982 delta.dx += cpd.x - lpd.x;
5983 delta.dy += cpd.y - lpd.y;
5984
5985 if (first) {
5986 commonDeltaX = delta.dx;
5987 commonDeltaY = delta.dy;
5988 } else {
5989 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5990 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5991 }
5992 }
5993
5994 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5995 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5996 float dist[MAX_POINTER_ID + 1];
5997 int32_t distOverThreshold = 0;
5998 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5999 uint32_t id = idBits.clearFirstMarkedBit();
6000 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6001 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
6002 delta.dy * mPointerYZoomScale);
6003 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
6004 distOverThreshold += 1;
6005 }
6006 }
6007
6008 // Only transition when at least two pointers have moved further than
6009 // the minimum distance threshold.
6010 if (distOverThreshold >= 2) {
6011 if (currentFingerCount > 2) {
6012 // There are more than two pointers, switch to FREEFORM.
6013#if DEBUG_GESTURES
6014 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
6015 currentFingerCount);
6016#endif
6017 *outCancelPreviousGesture = true;
6018 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6019 } else {
6020 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07006021 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006022 uint32_t id1 = idBits.clearFirstMarkedBit();
6023 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07006024 const RawPointerData::Pointer& p1 =
6025 mCurrentRawState.rawPointerData.pointerForId(id1);
6026 const RawPointerData::Pointer& p2 =
6027 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006028 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6029 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6030 // There are two pointers but they are too far apart for a SWIPE,
6031 // switch to FREEFORM.
6032#if DEBUG_GESTURES
6033 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6034 mutualDistance, mPointerGestureMaxSwipeWidth);
6035#endif
6036 *outCancelPreviousGesture = true;
6037 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6038 } else {
6039 // There are two pointers. Wait for both pointers to start moving
6040 // before deciding whether this is a SWIPE or FREEFORM gesture.
6041 float dist1 = dist[id1];
6042 float dist2 = dist[id2];
6043 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6044 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6045 // Calculate the dot product of the displacement vectors.
6046 // When the vectors are oriented in approximately the same direction,
6047 // the angle betweeen them is near zero and the cosine of the angle
6048 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6049 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6050 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6051 float dx1 = delta1.dx * mPointerXZoomScale;
6052 float dy1 = delta1.dy * mPointerYZoomScale;
6053 float dx2 = delta2.dx * mPointerXZoomScale;
6054 float dy2 = delta2.dy * mPointerYZoomScale;
6055 float dot = dx1 * dx2 + dy1 * dy2;
6056 float cosine = dot / (dist1 * dist2); // denominator always > 0
6057 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6058 // Pointers are moving in the same direction. Switch to SWIPE.
6059#if DEBUG_GESTURES
6060 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6061 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6062 "cosine %0.3f >= %0.3f",
6063 dist1, mConfig.pointerGestureMultitouchMinDistance,
6064 dist2, mConfig.pointerGestureMultitouchMinDistance,
6065 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6066#endif
6067 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6068 } else {
6069 // Pointers are moving in different directions. Switch to FREEFORM.
6070#if DEBUG_GESTURES
6071 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6072 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6073 "cosine %0.3f < %0.3f",
6074 dist1, mConfig.pointerGestureMultitouchMinDistance,
6075 dist2, mConfig.pointerGestureMultitouchMinDistance,
6076 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6077#endif
6078 *outCancelPreviousGesture = true;
6079 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6080 }
6081 }
6082 }
6083 }
6084 }
6085 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6086 // Switch from SWIPE to FREEFORM if additional pointers go down.
6087 // Cancel previous gesture.
6088 if (currentFingerCount > 2) {
6089#if DEBUG_GESTURES
6090 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6091 currentFingerCount);
6092#endif
6093 *outCancelPreviousGesture = true;
6094 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6095 }
6096 }
6097
6098 // Move the reference points based on the overall group motion of the fingers
6099 // except in PRESS mode while waiting for a transition to occur.
6100 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6101 && (commonDeltaX || commonDeltaY)) {
6102 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6103 uint32_t id = idBits.clearFirstMarkedBit();
6104 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6105 delta.dx = 0;
6106 delta.dy = 0;
6107 }
6108
6109 mPointerGesture.referenceTouchX += commonDeltaX;
6110 mPointerGesture.referenceTouchY += commonDeltaY;
6111
6112 commonDeltaX *= mPointerXMovementScale;
6113 commonDeltaY *= mPointerYMovementScale;
6114
6115 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6116 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6117
6118 mPointerGesture.referenceGestureX += commonDeltaX;
6119 mPointerGesture.referenceGestureY += commonDeltaY;
6120 }
6121
6122 // Report gestures.
6123 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6124 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6125 // PRESS or SWIPE mode.
6126#if DEBUG_GESTURES
6127 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6128 "activeGestureId=%d, currentTouchPointerCount=%d",
6129 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6130#endif
6131 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6132
6133 mPointerGesture.currentGestureIdBits.clear();
6134 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6135 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6136 mPointerGesture.currentGestureProperties[0].clear();
6137 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6138 mPointerGesture.currentGestureProperties[0].toolType =
6139 AMOTION_EVENT_TOOL_TYPE_FINGER;
6140 mPointerGesture.currentGestureCoords[0].clear();
6141 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6142 mPointerGesture.referenceGestureX);
6143 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6144 mPointerGesture.referenceGestureY);
6145 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6146 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6147 // FREEFORM mode.
6148#if DEBUG_GESTURES
6149 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6150 "activeGestureId=%d, currentTouchPointerCount=%d",
6151 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6152#endif
6153 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6154
6155 mPointerGesture.currentGestureIdBits.clear();
6156
6157 BitSet32 mappedTouchIdBits;
6158 BitSet32 usedGestureIdBits;
6159 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6160 // Initially, assign the active gesture id to the active touch point
6161 // if there is one. No other touch id bits are mapped yet.
6162 if (!*outCancelPreviousGesture) {
6163 mappedTouchIdBits.markBit(activeTouchId);
6164 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6165 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6166 mPointerGesture.activeGestureId;
6167 } else {
6168 mPointerGesture.activeGestureId = -1;
6169 }
6170 } else {
6171 // Otherwise, assume we mapped all touches from the previous frame.
6172 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006173 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6174 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6176
6177 // Check whether we need to choose a new active gesture id because the
6178 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006179 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6180 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006181 !upTouchIdBits.isEmpty(); ) {
6182 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6183 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6184 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6185 mPointerGesture.activeGestureId = -1;
6186 break;
6187 }
6188 }
6189 }
6190
6191#if DEBUG_GESTURES
6192 ALOGD("Gestures: FREEFORM follow up "
6193 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6194 "activeGestureId=%d",
6195 mappedTouchIdBits.value, usedGestureIdBits.value,
6196 mPointerGesture.activeGestureId);
6197#endif
6198
Michael Wright842500e2015-03-13 17:32:02 -07006199 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200 for (uint32_t i = 0; i < currentFingerCount; i++) {
6201 uint32_t touchId = idBits.clearFirstMarkedBit();
6202 uint32_t gestureId;
6203 if (!mappedTouchIdBits.hasBit(touchId)) {
6204 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6205 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6206#if DEBUG_GESTURES
6207 ALOGD("Gestures: FREEFORM "
6208 "new mapping for touch id %d -> gesture id %d",
6209 touchId, gestureId);
6210#endif
6211 } else {
6212 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6213#if DEBUG_GESTURES
6214 ALOGD("Gestures: FREEFORM "
6215 "existing mapping for touch id %d -> gesture id %d",
6216 touchId, gestureId);
6217#endif
6218 }
6219 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6220 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6221
6222 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006223 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006224 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6225 * mPointerXZoomScale;
6226 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6227 * mPointerYZoomScale;
6228 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6229
6230 mPointerGesture.currentGestureProperties[i].clear();
6231 mPointerGesture.currentGestureProperties[i].id = gestureId;
6232 mPointerGesture.currentGestureProperties[i].toolType =
6233 AMOTION_EVENT_TOOL_TYPE_FINGER;
6234 mPointerGesture.currentGestureCoords[i].clear();
6235 mPointerGesture.currentGestureCoords[i].setAxisValue(
6236 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6237 mPointerGesture.currentGestureCoords[i].setAxisValue(
6238 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6239 mPointerGesture.currentGestureCoords[i].setAxisValue(
6240 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6241 }
6242
6243 if (mPointerGesture.activeGestureId < 0) {
6244 mPointerGesture.activeGestureId =
6245 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6246#if DEBUG_GESTURES
6247 ALOGD("Gestures: FREEFORM new "
6248 "activeGestureId=%d", mPointerGesture.activeGestureId);
6249#endif
6250 }
6251 }
6252 }
6253
Michael Wright842500e2015-03-13 17:32:02 -07006254 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006255
6256#if DEBUG_GESTURES
6257 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6258 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6259 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6260 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6261 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6262 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6263 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6264 uint32_t id = idBits.clearFirstMarkedBit();
6265 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6266 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6267 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6268 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6269 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6270 id, index, properties.toolType,
6271 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6272 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6273 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6274 }
6275 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6276 uint32_t id = idBits.clearFirstMarkedBit();
6277 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6278 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6279 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6280 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6281 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6282 id, index, properties.toolType,
6283 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6284 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6285 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6286 }
6287#endif
6288 return true;
6289}
6290
6291void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6292 mPointerSimple.currentCoords.clear();
6293 mPointerSimple.currentProperties.clear();
6294
6295 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006296 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6297 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6298 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6299 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6300 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006301 mPointerController->setPosition(x, y);
6302
Michael Wright842500e2015-03-13 17:32:02 -07006303 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006304 down = !hovering;
6305
6306 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006307 mPointerSimple.currentCoords.copyFrom(
6308 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6310 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6311 mPointerSimple.currentProperties.id = 0;
6312 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006313 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 } else {
6315 down = false;
6316 hovering = false;
6317 }
6318
6319 dispatchPointerSimple(when, policyFlags, down, hovering);
6320}
6321
6322void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6323 abortPointerSimple(when, policyFlags);
6324}
6325
6326void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6327 mPointerSimple.currentCoords.clear();
6328 mPointerSimple.currentProperties.clear();
6329
6330 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006331 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6332 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6333 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006334 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006335 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6336 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006337 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006338 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006339 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006340 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006341 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 * mPointerYMovementScale;
6343
6344 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6345 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6346
6347 mPointerController->move(deltaX, deltaY);
6348 } else {
6349 mPointerVelocityControl.reset();
6350 }
6351
Michael Wright842500e2015-03-13 17:32:02 -07006352 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006353 hovering = !down;
6354
6355 float x, y;
6356 mPointerController->getPosition(&x, &y);
6357 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006358 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006359 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6360 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6361 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6362 hovering ? 0.0f : 1.0f);
6363 mPointerSimple.currentProperties.id = 0;
6364 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006365 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 } else {
6367 mPointerVelocityControl.reset();
6368
6369 down = false;
6370 hovering = false;
6371 }
6372
6373 dispatchPointerSimple(when, policyFlags, down, hovering);
6374}
6375
6376void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6377 abortPointerSimple(when, policyFlags);
6378
6379 mPointerVelocityControl.reset();
6380}
6381
6382void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6383 bool down, bool hovering) {
6384 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006385 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386
Garfield Tan00f511d2019-06-12 16:55:40 -07006387 if (down || hovering) {
6388 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6389 mPointerController->clearSpots();
6390 mPointerController->setButtonState(mCurrentRawState.buttonState);
6391 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6392 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6393 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006394 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006395 displayId = mPointerController->getDisplayId();
6396
6397 float xCursorPosition;
6398 float yCursorPosition;
6399 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400
6401 if (mPointerSimple.down && !down) {
6402 mPointerSimple.down = false;
6403
6404 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006405 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6406 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6407 mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006408 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6409 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6410 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6411 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412 getListener()->notifyMotion(&args);
6413 }
6414
6415 if (mPointerSimple.hovering && !hovering) {
6416 mPointerSimple.hovering = false;
6417
6418 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006419 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6420 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6421 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006422 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6423 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6424 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6425 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426 getListener()->notifyMotion(&args);
6427 }
6428
6429 if (down) {
6430 if (!mPointerSimple.down) {
6431 mPointerSimple.down = true;
6432 mPointerSimple.downTime = when;
6433
6434 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006435 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6436 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6437 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006438 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6439 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6440 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6441 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006442 getListener()->notifyMotion(&args);
6443 }
6444
6445 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006446 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6447 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6448 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006449 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6450 &mPointerSimple.currentCoords, mOrientedXPrecision,
6451 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6452 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453 getListener()->notifyMotion(&args);
6454 }
6455
6456 if (hovering) {
6457 if (!mPointerSimple.hovering) {
6458 mPointerSimple.hovering = true;
6459
6460 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006461 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6462 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6463 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006464 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6465 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6466 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6467 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006468 getListener()->notifyMotion(&args);
6469 }
6470
6471 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006472 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6473 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6474 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006475 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6476 &mPointerSimple.currentCoords, mOrientedXPrecision,
6477 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6478 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006479 getListener()->notifyMotion(&args);
6480 }
6481
Michael Wright842500e2015-03-13 17:32:02 -07006482 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6483 float vscroll = mCurrentRawState.rawVScroll;
6484 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006485 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6486 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006487
6488 // Send scroll.
6489 PointerCoords pointerCoords;
6490 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6491 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6492 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6493
Garfield Tan00f511d2019-06-12 16:55:40 -07006494 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6495 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6496 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006497 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6498 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
6499 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6500 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 getListener()->notifyMotion(&args);
6502 }
6503
6504 // Save state.
6505 if (down || hovering) {
6506 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6507 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6508 } else {
6509 mPointerSimple.reset();
6510 }
6511}
6512
6513void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6514 mPointerSimple.currentCoords.clear();
6515 mPointerSimple.currentProperties.clear();
6516
6517 dispatchPointerSimple(when, policyFlags, false, false);
6518}
6519
6520void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006521 int32_t action, int32_t actionButton, int32_t flags,
6522 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6523 const PointerProperties* properties,
6524 const PointerCoords* coords, const uint32_t* idToIndex,
6525 BitSet32 idBits, int32_t changedId, float xPrecision,
6526 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006527 PointerCoords pointerCoords[MAX_POINTERS];
6528 PointerProperties pointerProperties[MAX_POINTERS];
6529 uint32_t pointerCount = 0;
6530 while (!idBits.isEmpty()) {
6531 uint32_t id = idBits.clearFirstMarkedBit();
6532 uint32_t index = idToIndex[id];
6533 pointerProperties[pointerCount].copyFrom(properties[index]);
6534 pointerCoords[pointerCount].copyFrom(coords[index]);
6535
6536 if (changedId >= 0 && id == uint32_t(changedId)) {
6537 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6538 }
6539
6540 pointerCount += 1;
6541 }
6542
6543 ALOG_ASSERT(pointerCount != 0);
6544
6545 if (changedId >= 0 && pointerCount == 1) {
6546 // Replace initial down and final up action.
6547 // We can compare the action without masking off the changed pointer index
6548 // because we know the index is 0.
6549 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6550 action = AMOTION_EVENT_ACTION_DOWN;
6551 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6552 action = AMOTION_EVENT_ACTION_UP;
6553 } else {
6554 // Can't happen.
6555 ALOG_ASSERT(false);
6556 }
6557 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006558 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6559 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6560 if (mDeviceMode == DEVICE_MODE_POINTER) {
6561 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6562 }
Arthur Hung2c9a3342019-07-23 14:18:59 +08006563 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006564 const int32_t deviceId = getDeviceId();
6565 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006566 std::for_each(frames.begin(), frames.end(),
6567 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006568 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6569 policyFlags, action, actionButton, flags, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006570 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
6571 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
6572 downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573 getListener()->notifyMotion(&args);
6574}
6575
6576bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6577 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6578 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6579 BitSet32 idBits) const {
6580 bool changed = false;
6581 while (!idBits.isEmpty()) {
6582 uint32_t id = idBits.clearFirstMarkedBit();
6583 uint32_t inIndex = inIdToIndex[id];
6584 uint32_t outIndex = outIdToIndex[id];
6585
6586 const PointerProperties& curInProperties = inProperties[inIndex];
6587 const PointerCoords& curInCoords = inCoords[inIndex];
6588 PointerProperties& curOutProperties = outProperties[outIndex];
6589 PointerCoords& curOutCoords = outCoords[outIndex];
6590
6591 if (curInProperties != curOutProperties) {
6592 curOutProperties.copyFrom(curInProperties);
6593 changed = true;
6594 }
6595
6596 if (curInCoords != curOutCoords) {
6597 curOutCoords.copyFrom(curInCoords);
6598 changed = true;
6599 }
6600 }
6601 return changed;
6602}
6603
6604void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006605 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006606 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6607 }
6608}
6609
Jeff Brownc9aa6282015-02-11 19:03:28 -08006610void TouchInputMapper::cancelTouch(nsecs_t when) {
6611 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006612 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006613}
6614
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006616 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006617 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006619 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6620 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6621 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006622}
6623
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006624const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006625
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006626 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006627#if DEBUG_VIRTUAL_KEYS
6628 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6629 "left=%d, top=%d, right=%d, bottom=%d",
6630 x, y,
6631 virtualKey.keyCode, virtualKey.scanCode,
6632 virtualKey.hitLeft, virtualKey.hitTop,
6633 virtualKey.hitRight, virtualKey.hitBottom);
6634#endif
6635
6636 if (virtualKey.isHit(x, y)) {
6637 return & virtualKey;
6638 }
6639 }
6640
Yi Kong9b14ac62018-07-17 13:48:38 -07006641 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006642}
6643
Michael Wright842500e2015-03-13 17:32:02 -07006644void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6645 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6646 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647
Michael Wright842500e2015-03-13 17:32:02 -07006648 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006649
6650 if (currentPointerCount == 0) {
6651 // No pointers to assign.
6652 return;
6653 }
6654
6655 if (lastPointerCount == 0) {
6656 // All pointers are new.
6657 for (uint32_t i = 0; i < currentPointerCount; i++) {
6658 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006659 current->rawPointerData.pointers[i].id = id;
6660 current->rawPointerData.idToIndex[id] = i;
6661 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006662 }
6663 return;
6664 }
6665
6666 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006667 && current->rawPointerData.pointers[0].toolType
6668 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006669 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006670 uint32_t id = last->rawPointerData.pointers[0].id;
6671 current->rawPointerData.pointers[0].id = id;
6672 current->rawPointerData.idToIndex[id] = 0;
6673 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674 return;
6675 }
6676
6677 // General case.
6678 // We build a heap of squared euclidean distances between current and last pointers
6679 // associated with the current and last pointer indices. Then, we find the best
6680 // match (by distance) for each current pointer.
6681 // The pointers must have the same tool type but it is possible for them to
6682 // transition from hovering to touching or vice-versa while retaining the same id.
6683 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6684
6685 uint32_t heapSize = 0;
6686 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6687 currentPointerIndex++) {
6688 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6689 lastPointerIndex++) {
6690 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006691 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006692 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006693 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006694 if (currentPointer.toolType == lastPointer.toolType) {
6695 int64_t deltaX = currentPointer.x - lastPointer.x;
6696 int64_t deltaY = currentPointer.y - lastPointer.y;
6697
6698 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6699
6700 // Insert new element into the heap (sift up).
6701 heap[heapSize].currentPointerIndex = currentPointerIndex;
6702 heap[heapSize].lastPointerIndex = lastPointerIndex;
6703 heap[heapSize].distance = distance;
6704 heapSize += 1;
6705 }
6706 }
6707 }
6708
6709 // Heapify
6710 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6711 startIndex -= 1;
6712 for (uint32_t parentIndex = startIndex; ;) {
6713 uint32_t childIndex = parentIndex * 2 + 1;
6714 if (childIndex >= heapSize) {
6715 break;
6716 }
6717
6718 if (childIndex + 1 < heapSize
6719 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6720 childIndex += 1;
6721 }
6722
6723 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6724 break;
6725 }
6726
6727 swap(heap[parentIndex], heap[childIndex]);
6728 parentIndex = childIndex;
6729 }
6730 }
6731
6732#if DEBUG_POINTER_ASSIGNMENT
6733 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6734 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006735 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006736 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6737 heap[i].distance);
6738 }
6739#endif
6740
6741 // Pull matches out by increasing order of distance.
6742 // To avoid reassigning pointers that have already been matched, the loop keeps track
6743 // of which last and current pointers have been matched using the matchedXXXBits variables.
6744 // It also tracks the used pointer id bits.
6745 BitSet32 matchedLastBits(0);
6746 BitSet32 matchedCurrentBits(0);
6747 BitSet32 usedIdBits(0);
6748 bool first = true;
6749 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6750 while (heapSize > 0) {
6751 if (first) {
6752 // The first time through the loop, we just consume the root element of
6753 // the heap (the one with smallest distance).
6754 first = false;
6755 } else {
6756 // Previous iterations consumed the root element of the heap.
6757 // Pop root element off of the heap (sift down).
6758 heap[0] = heap[heapSize];
6759 for (uint32_t parentIndex = 0; ;) {
6760 uint32_t childIndex = parentIndex * 2 + 1;
6761 if (childIndex >= heapSize) {
6762 break;
6763 }
6764
6765 if (childIndex + 1 < heapSize
6766 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6767 childIndex += 1;
6768 }
6769
6770 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6771 break;
6772 }
6773
6774 swap(heap[parentIndex], heap[childIndex]);
6775 parentIndex = childIndex;
6776 }
6777
6778#if DEBUG_POINTER_ASSIGNMENT
6779 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6780 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006781 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006782 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6783 heap[i].distance);
6784 }
6785#endif
6786 }
6787
6788 heapSize -= 1;
6789
6790 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6791 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6792
6793 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6794 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6795
6796 matchedCurrentBits.markBit(currentPointerIndex);
6797 matchedLastBits.markBit(lastPointerIndex);
6798
Michael Wright842500e2015-03-13 17:32:02 -07006799 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6800 current->rawPointerData.pointers[currentPointerIndex].id = id;
6801 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6802 current->rawPointerData.markIdBit(id,
6803 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006804 usedIdBits.markBit(id);
6805
6806#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006807 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6808 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006809 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6810#endif
6811 break;
6812 }
6813 }
6814
6815 // Assign fresh ids to pointers that were not matched in the process.
6816 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6817 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6818 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6819
Michael Wright842500e2015-03-13 17:32:02 -07006820 current->rawPointerData.pointers[currentPointerIndex].id = id;
6821 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6822 current->rawPointerData.markIdBit(id,
6823 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006824
6825#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006826 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006827#endif
6828 }
6829}
6830
6831int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6832 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6833 return AKEY_STATE_VIRTUAL;
6834 }
6835
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006836 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006837 if (virtualKey.keyCode == keyCode) {
6838 return AKEY_STATE_UP;
6839 }
6840 }
6841
6842 return AKEY_STATE_UNKNOWN;
6843}
6844
6845int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6846 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6847 return AKEY_STATE_VIRTUAL;
6848 }
6849
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006850 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006851 if (virtualKey.scanCode == scanCode) {
6852 return AKEY_STATE_UP;
6853 }
6854 }
6855
6856 return AKEY_STATE_UNKNOWN;
6857}
6858
6859bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6860 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006861 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006862 for (size_t i = 0; i < numCodes; i++) {
6863 if (virtualKey.keyCode == keyCodes[i]) {
6864 outFlags[i] = 1;
6865 }
6866 }
6867 }
6868
6869 return true;
6870}
6871
Arthur Hung2c9a3342019-07-23 14:18:59 +08006872std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
Arthur Hungc23540e2018-11-29 20:42:11 +08006873 if (mParameters.hasAssociatedDisplay) {
6874 if (mDeviceMode == DEVICE_MODE_POINTER) {
6875 return std::make_optional(mPointerController->getDisplayId());
6876 } else {
6877 return std::make_optional(mViewport.displayId);
6878 }
6879 }
6880 return std::nullopt;
6881}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006882
6883// --- SingleTouchInputMapper ---
6884
6885SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6886 TouchInputMapper(device) {
6887}
6888
6889SingleTouchInputMapper::~SingleTouchInputMapper() {
6890}
6891
6892void SingleTouchInputMapper::reset(nsecs_t when) {
6893 mSingleTouchMotionAccumulator.reset(getDevice());
6894
6895 TouchInputMapper::reset(when);
6896}
6897
6898void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6899 TouchInputMapper::process(rawEvent);
6900
6901 mSingleTouchMotionAccumulator.process(rawEvent);
6902}
6903
Michael Wright842500e2015-03-13 17:32:02 -07006904void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006905 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006906 outState->rawPointerData.pointerCount = 1;
6907 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006908
6909 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6910 && (mTouchButtonAccumulator.isHovering()
6911 || (mRawPointerAxes.pressure.valid
6912 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006913 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006914
Michael Wright842500e2015-03-13 17:32:02 -07006915 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006916 outPointer.id = 0;
6917 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6918 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6919 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6920 outPointer.touchMajor = 0;
6921 outPointer.touchMinor = 0;
6922 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6923 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6924 outPointer.orientation = 0;
6925 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6926 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6927 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6928 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6929 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6930 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6931 }
6932 outPointer.isHovering = isHovering;
6933 }
6934}
6935
6936void SingleTouchInputMapper::configureRawPointerAxes() {
6937 TouchInputMapper::configureRawPointerAxes();
6938
6939 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6940 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6941 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6942 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6943 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6944 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6945 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6946}
6947
6948bool SingleTouchInputMapper::hasStylus() const {
6949 return mTouchButtonAccumulator.hasStylus();
6950}
6951
6952
6953// --- MultiTouchInputMapper ---
6954
6955MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6956 TouchInputMapper(device) {
6957}
6958
6959MultiTouchInputMapper::~MultiTouchInputMapper() {
6960}
6961
6962void MultiTouchInputMapper::reset(nsecs_t when) {
6963 mMultiTouchMotionAccumulator.reset(getDevice());
6964
6965 mPointerIdBits.clear();
6966
6967 TouchInputMapper::reset(when);
6968}
6969
6970void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6971 TouchInputMapper::process(rawEvent);
6972
6973 mMultiTouchMotionAccumulator.process(rawEvent);
6974}
6975
Michael Wright842500e2015-03-13 17:32:02 -07006976void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006977 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6978 size_t outCount = 0;
6979 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006980 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006981
6982 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6983 const MultiTouchMotionAccumulator::Slot* inSlot =
6984 mMultiTouchMotionAccumulator.getSlot(inIndex);
6985 if (!inSlot->isInUse()) {
6986 continue;
6987 }
6988
6989 if (outCount >= MAX_POINTERS) {
6990#if DEBUG_POINTERS
6991 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6992 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006993 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006994#endif
6995 break; // too many fingers!
6996 }
6997
Michael Wright842500e2015-03-13 17:32:02 -07006998 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006999 outPointer.x = inSlot->getX();
7000 outPointer.y = inSlot->getY();
7001 outPointer.pressure = inSlot->getPressure();
7002 outPointer.touchMajor = inSlot->getTouchMajor();
7003 outPointer.touchMinor = inSlot->getTouchMinor();
7004 outPointer.toolMajor = inSlot->getToolMajor();
7005 outPointer.toolMinor = inSlot->getToolMinor();
7006 outPointer.orientation = inSlot->getOrientation();
7007 outPointer.distance = inSlot->getDistance();
7008 outPointer.tiltX = 0;
7009 outPointer.tiltY = 0;
7010
7011 outPointer.toolType = inSlot->getToolType();
7012 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7013 outPointer.toolType = mTouchButtonAccumulator.getToolType();
7014 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7015 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
7016 }
7017 }
7018
7019 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
7020 && (mTouchButtonAccumulator.isHovering()
7021 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
7022 outPointer.isHovering = isHovering;
7023
7024 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08007025 if (mHavePointerIds) {
7026 int32_t trackingId = inSlot->getTrackingId();
7027 int32_t id = -1;
7028 if (trackingId >= 0) {
7029 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7030 uint32_t n = idBits.clearFirstMarkedBit();
7031 if (mPointerTrackingIdMap[n] == trackingId) {
7032 id = n;
7033 }
7034 }
7035
7036 if (id < 0 && !mPointerIdBits.isFull()) {
7037 id = mPointerIdBits.markFirstUnmarkedBit();
7038 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007039 }
Michael Wright842500e2015-03-13 17:32:02 -07007040 }
gaoshang1a632de2016-08-24 10:23:50 +08007041 if (id < 0) {
7042 mHavePointerIds = false;
7043 outState->rawPointerData.clearIdBits();
7044 newPointerIdBits.clear();
7045 } else {
7046 outPointer.id = id;
7047 outState->rawPointerData.idToIndex[id] = outCount;
7048 outState->rawPointerData.markIdBit(id, isHovering);
7049 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007050 }
Michael Wright842500e2015-03-13 17:32:02 -07007051 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007052 outCount += 1;
7053 }
7054
Michael Wright842500e2015-03-13 17:32:02 -07007055 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007056 mPointerIdBits = newPointerIdBits;
7057
7058 mMultiTouchMotionAccumulator.finishSync();
7059}
7060
7061void MultiTouchInputMapper::configureRawPointerAxes() {
7062 TouchInputMapper::configureRawPointerAxes();
7063
7064 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7065 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7066 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7067 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7068 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7069 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7070 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7071 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7072 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7073 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7074 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7075
7076 if (mRawPointerAxes.trackingId.valid
7077 && mRawPointerAxes.slot.valid
7078 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7079 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7080 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007081 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7082 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007083 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007084 slotCount = MAX_SLOTS;
7085 }
7086 mMultiTouchMotionAccumulator.configure(getDevice(),
7087 slotCount, true /*usingSlotsProtocol*/);
7088 } else {
7089 mMultiTouchMotionAccumulator.configure(getDevice(),
7090 MAX_POINTERS, false /*usingSlotsProtocol*/);
7091 }
7092}
7093
7094bool MultiTouchInputMapper::hasStylus() const {
7095 return mMultiTouchMotionAccumulator.hasStylus()
7096 || mTouchButtonAccumulator.hasStylus();
7097}
7098
Michael Wright842500e2015-03-13 17:32:02 -07007099// --- ExternalStylusInputMapper
7100
7101ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7102 InputMapper(device) {
7103
7104}
7105
7106uint32_t ExternalStylusInputMapper::getSources() {
7107 return AINPUT_SOURCE_STYLUS;
7108}
7109
7110void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7111 InputMapper::populateDeviceInfo(info);
7112 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7113 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7114}
7115
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007116void ExternalStylusInputMapper::dump(std::string& dump) {
7117 dump += INDENT2 "External Stylus Input Mapper:\n";
7118 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007119 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007120 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007121 dumpStylusState(dump, mStylusState);
7122}
7123
7124void ExternalStylusInputMapper::configure(nsecs_t when,
7125 const InputReaderConfiguration* config, uint32_t changes) {
7126 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7127 mTouchButtonAccumulator.configure(getDevice());
7128}
7129
7130void ExternalStylusInputMapper::reset(nsecs_t when) {
7131 InputDevice* device = getDevice();
7132 mSingleTouchMotionAccumulator.reset(device);
7133 mTouchButtonAccumulator.reset(device);
7134 InputMapper::reset(when);
7135}
7136
7137void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7138 mSingleTouchMotionAccumulator.process(rawEvent);
7139 mTouchButtonAccumulator.process(rawEvent);
7140
7141 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7142 sync(rawEvent->when);
7143 }
7144}
7145
7146void ExternalStylusInputMapper::sync(nsecs_t when) {
7147 mStylusState.clear();
7148
7149 mStylusState.when = when;
7150
Michael Wright45ccacf2015-04-21 19:01:58 +01007151 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7152 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7153 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7154 }
7155
Michael Wright842500e2015-03-13 17:32:02 -07007156 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7157 if (mRawPressureAxis.valid) {
7158 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7159 } else if (mTouchButtonAccumulator.isToolActive()) {
7160 mStylusState.pressure = 1.0f;
7161 } else {
7162 mStylusState.pressure = 0.0f;
7163 }
7164
7165 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007166
7167 mContext->dispatchExternalStylusState(mStylusState);
7168}
7169
Michael Wrightd02c5b62014-02-10 15:10:22 -08007170
7171// --- JoystickInputMapper ---
7172
7173JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7174 InputMapper(device) {
7175}
7176
7177JoystickInputMapper::~JoystickInputMapper() {
7178}
7179
7180uint32_t JoystickInputMapper::getSources() {
7181 return AINPUT_SOURCE_JOYSTICK;
7182}
7183
7184void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7185 InputMapper::populateDeviceInfo(info);
7186
7187 for (size_t i = 0; i < mAxes.size(); i++) {
7188 const Axis& axis = mAxes.valueAt(i);
7189 addMotionRange(axis.axisInfo.axis, axis, info);
7190
7191 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7192 addMotionRange(axis.axisInfo.highAxis, axis, info);
7193
7194 }
7195 }
7196}
7197
7198void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7199 InputDeviceInfo* info) {
7200 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7201 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7202 /* In order to ease the transition for developers from using the old axes
7203 * to the newer, more semantically correct axes, we'll continue to register
7204 * the old axes as duplicates of their corresponding new ones. */
7205 int32_t compatAxis = getCompatAxis(axisId);
7206 if (compatAxis >= 0) {
7207 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7208 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7209 }
7210}
7211
7212/* A mapping from axes the joystick actually has to the axes that should be
7213 * artificially created for compatibility purposes.
7214 * Returns -1 if no compatibility axis is needed. */
7215int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7216 switch(axis) {
7217 case AMOTION_EVENT_AXIS_LTRIGGER:
7218 return AMOTION_EVENT_AXIS_BRAKE;
7219 case AMOTION_EVENT_AXIS_RTRIGGER:
7220 return AMOTION_EVENT_AXIS_GAS;
7221 }
7222 return -1;
7223}
7224
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007225void JoystickInputMapper::dump(std::string& dump) {
7226 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007227
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007228 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007229 size_t numAxes = mAxes.size();
7230 for (size_t i = 0; i < numAxes; i++) {
7231 const Axis& axis = mAxes.valueAt(i);
7232 const char* label = getAxisLabel(axis.axisInfo.axis);
7233 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007234 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007235 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007236 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007237 }
7238 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7239 label = getAxisLabel(axis.axisInfo.highAxis);
7240 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007241 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007242 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007243 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007244 axis.axisInfo.splitValue);
7245 }
7246 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007247 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007248 }
7249
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007250 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 -08007251 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007252 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007253 "highScale=%0.5f, highOffset=%0.5f\n",
7254 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007255 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007256 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7257 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7258 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7259 }
7260}
7261
7262void JoystickInputMapper::configure(nsecs_t when,
7263 const InputReaderConfiguration* config, uint32_t changes) {
7264 InputMapper::configure(when, config, changes);
7265
7266 if (!changes) { // first time only
7267 // Collect all axes.
7268 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7269 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7270 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7271 continue; // axis must be claimed by a different device
7272 }
7273
7274 RawAbsoluteAxisInfo rawAxisInfo;
7275 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7276 if (rawAxisInfo.valid) {
7277 // Map axis.
7278 AxisInfo axisInfo;
7279 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7280 if (!explicitlyMapped) {
7281 // Axis is not explicitly mapped, will choose a generic axis later.
7282 axisInfo.mode = AxisInfo::MODE_NORMAL;
7283 axisInfo.axis = -1;
7284 }
7285
7286 // Apply flat override.
7287 int32_t rawFlat = axisInfo.flatOverride < 0
7288 ? rawAxisInfo.flat : axisInfo.flatOverride;
7289
7290 // Calculate scaling factors and limits.
7291 Axis axis;
7292 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7293 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7294 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7295 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7296 scale, 0.0f, highScale, 0.0f,
7297 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7298 rawAxisInfo.resolution * scale);
7299 } else if (isCenteredAxis(axisInfo.axis)) {
7300 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7301 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7302 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7303 scale, offset, scale, offset,
7304 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7305 rawAxisInfo.resolution * scale);
7306 } else {
7307 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7308 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7309 scale, 0.0f, scale, 0.0f,
7310 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7311 rawAxisInfo.resolution * scale);
7312 }
7313
7314 // To eliminate noise while the joystick is at rest, filter out small variations
7315 // in axis values up front.
7316 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7317
7318 mAxes.add(abs, axis);
7319 }
7320 }
7321
7322 // If there are too many axes, start dropping them.
7323 // Prefer to keep explicitly mapped axes.
7324 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007325 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007326 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007327 pruneAxes(true);
7328 pruneAxes(false);
7329 }
7330
7331 // Assign generic axis ids to remaining axes.
7332 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7333 size_t numAxes = mAxes.size();
7334 for (size_t i = 0; i < numAxes; i++) {
7335 Axis& axis = mAxes.editValueAt(i);
7336 if (axis.axisInfo.axis < 0) {
7337 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7338 && haveAxis(nextGenericAxisId)) {
7339 nextGenericAxisId += 1;
7340 }
7341
7342 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7343 axis.axisInfo.axis = nextGenericAxisId;
7344 nextGenericAxisId += 1;
7345 } else {
7346 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7347 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007348 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007349 mAxes.removeItemsAt(i--);
7350 numAxes -= 1;
7351 }
7352 }
7353 }
7354 }
7355}
7356
7357bool JoystickInputMapper::haveAxis(int32_t axisId) {
7358 size_t numAxes = mAxes.size();
7359 for (size_t i = 0; i < numAxes; i++) {
7360 const Axis& axis = mAxes.valueAt(i);
7361 if (axis.axisInfo.axis == axisId
7362 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7363 && axis.axisInfo.highAxis == axisId)) {
7364 return true;
7365 }
7366 }
7367 return false;
7368}
7369
7370void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7371 size_t i = mAxes.size();
7372 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7373 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7374 continue;
7375 }
7376 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007377 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007378 mAxes.removeItemsAt(i);
7379 }
7380}
7381
7382bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7383 switch (axis) {
7384 case AMOTION_EVENT_AXIS_X:
7385 case AMOTION_EVENT_AXIS_Y:
7386 case AMOTION_EVENT_AXIS_Z:
7387 case AMOTION_EVENT_AXIS_RX:
7388 case AMOTION_EVENT_AXIS_RY:
7389 case AMOTION_EVENT_AXIS_RZ:
7390 case AMOTION_EVENT_AXIS_HAT_X:
7391 case AMOTION_EVENT_AXIS_HAT_Y:
7392 case AMOTION_EVENT_AXIS_ORIENTATION:
7393 case AMOTION_EVENT_AXIS_RUDDER:
7394 case AMOTION_EVENT_AXIS_WHEEL:
7395 return true;
7396 default:
7397 return false;
7398 }
7399}
7400
7401void JoystickInputMapper::reset(nsecs_t when) {
7402 // Recenter all axes.
7403 size_t numAxes = mAxes.size();
7404 for (size_t i = 0; i < numAxes; i++) {
7405 Axis& axis = mAxes.editValueAt(i);
7406 axis.resetValue();
7407 }
7408
7409 InputMapper::reset(when);
7410}
7411
7412void JoystickInputMapper::process(const RawEvent* rawEvent) {
7413 switch (rawEvent->type) {
7414 case EV_ABS: {
7415 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7416 if (index >= 0) {
7417 Axis& axis = mAxes.editValueAt(index);
7418 float newValue, highNewValue;
7419 switch (axis.axisInfo.mode) {
7420 case AxisInfo::MODE_INVERT:
7421 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7422 * axis.scale + axis.offset;
7423 highNewValue = 0.0f;
7424 break;
7425 case AxisInfo::MODE_SPLIT:
7426 if (rawEvent->value < axis.axisInfo.splitValue) {
7427 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7428 * axis.scale + axis.offset;
7429 highNewValue = 0.0f;
7430 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7431 newValue = 0.0f;
7432 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7433 * axis.highScale + axis.highOffset;
7434 } else {
7435 newValue = 0.0f;
7436 highNewValue = 0.0f;
7437 }
7438 break;
7439 default:
7440 newValue = rawEvent->value * axis.scale + axis.offset;
7441 highNewValue = 0.0f;
7442 break;
7443 }
7444 axis.newValue = newValue;
7445 axis.highNewValue = highNewValue;
7446 }
7447 break;
7448 }
7449
7450 case EV_SYN:
7451 switch (rawEvent->code) {
7452 case SYN_REPORT:
7453 sync(rawEvent->when, false /*force*/);
7454 break;
7455 }
7456 break;
7457 }
7458}
7459
7460void JoystickInputMapper::sync(nsecs_t when, bool force) {
7461 if (!filterAxes(force)) {
7462 return;
7463 }
7464
7465 int32_t metaState = mContext->getGlobalMetaState();
7466 int32_t buttonState = 0;
7467
7468 PointerProperties pointerProperties;
7469 pointerProperties.clear();
7470 pointerProperties.id = 0;
7471 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7472
7473 PointerCoords pointerCoords;
7474 pointerCoords.clear();
7475
7476 size_t numAxes = mAxes.size();
7477 for (size_t i = 0; i < numAxes; i++) {
7478 const Axis& axis = mAxes.valueAt(i);
7479 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7480 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7481 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7482 axis.highCurrentValue);
7483 }
7484 }
7485
7486 // Moving a joystick axis should not wake the device because joysticks can
7487 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7488 // button will likely wake the device.
7489 // TODO: Use the input device configuration to control this behavior more finely.
7490 uint32_t policyFlags = 0;
7491
Prabir Pradhan42611e02018-11-27 14:04:02 -08007492 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007493 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7494 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07007495 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
7496 &pointerProperties, &pointerCoords, 0, 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07007497 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7498 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007499 getListener()->notifyMotion(&args);
7500}
7501
7502void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7503 int32_t axis, float value) {
7504 pointerCoords->setAxisValue(axis, value);
7505 /* In order to ease the transition for developers from using the old axes
7506 * to the newer, more semantically correct axes, we'll continue to produce
7507 * values for the old axes as mirrors of the value of their corresponding
7508 * new axes. */
7509 int32_t compatAxis = getCompatAxis(axis);
7510 if (compatAxis >= 0) {
7511 pointerCoords->setAxisValue(compatAxis, value);
7512 }
7513}
7514
7515bool JoystickInputMapper::filterAxes(bool force) {
7516 bool atLeastOneSignificantChange = force;
7517 size_t numAxes = mAxes.size();
7518 for (size_t i = 0; i < numAxes; i++) {
7519 Axis& axis = mAxes.editValueAt(i);
7520 if (force || hasValueChangedSignificantly(axis.filter,
7521 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7522 axis.currentValue = axis.newValue;
7523 atLeastOneSignificantChange = true;
7524 }
7525 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7526 if (force || hasValueChangedSignificantly(axis.filter,
7527 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7528 axis.highCurrentValue = axis.highNewValue;
7529 atLeastOneSignificantChange = true;
7530 }
7531 }
7532 }
7533 return atLeastOneSignificantChange;
7534}
7535
7536bool JoystickInputMapper::hasValueChangedSignificantly(
7537 float filter, float newValue, float currentValue, float min, float max) {
7538 if (newValue != currentValue) {
7539 // Filter out small changes in value unless the value is converging on the axis
7540 // bounds or center point. This is intended to reduce the amount of information
7541 // sent to applications by particularly noisy joysticks (such as PS3).
7542 if (fabs(newValue - currentValue) > filter
7543 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7544 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7545 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7546 return true;
7547 }
7548 }
7549 return false;
7550}
7551
7552bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7553 float filter, float newValue, float currentValue, float thresholdValue) {
7554 float newDistance = fabs(newValue - thresholdValue);
7555 if (newDistance < filter) {
7556 float oldDistance = fabs(currentValue - thresholdValue);
7557 if (newDistance < oldDistance) {
7558 return true;
7559 }
7560 }
7561 return false;
7562}
7563
7564} // namespace android