blob: 4631becee8ea979ceb65d3ca300e54304609178f [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);
822 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
823 // No associated display. By default, can dispatch to all displays.
824 if (!associatedDisplayId) {
825 return true;
826 }
827
828 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
829 ALOGW("Device has associated, but no associated display id.");
830 return true;
831 }
832
833 return *associatedDisplayId == displayId;
834}
835
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800836void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 AutoMutex _l(mLock);
838
839 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800840 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800842 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800843
844 for (size_t i = 0; i < mDevices.size(); i++) {
845 mDevices.valueAt(i)->dump(dump);
846 }
847
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800848 dump += INDENT "Configuration:\n";
849 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
851 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100854 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += "]\n";
857 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 mConfig.virtualKeyQuietTime * 0.000001f);
859
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800860 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
862 mConfig.pointerVelocityControlParameters.scale,
863 mConfig.pointerVelocityControlParameters.lowThreshold,
864 mConfig.pointerVelocityControlParameters.highThreshold,
865 mConfig.pointerVelocityControlParameters.acceleration);
866
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800867 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
869 mConfig.wheelVelocityControlParameters.scale,
870 mConfig.wheelVelocityControlParameters.lowThreshold,
871 mConfig.wheelVelocityControlParameters.highThreshold,
872 mConfig.wheelVelocityControlParameters.acceleration);
873
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800874 dump += StringPrintf(INDENT2 "PointerGesture:\n");
875 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800877 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800881 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700899
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800900 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700901 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902}
903
904void InputReader::monitor() {
905 // Acquire and release the lock to ensure that the reader has not deadlocked.
906 mLock.lock();
907 mEventHub->wake();
908 mReaderIsAliveCondition.wait(mLock);
909 mLock.unlock();
910
911 // Check the EventHub
912 mEventHub->monitor();
913}
914
915
916// --- InputReader::ContextImpl ---
917
918InputReader::ContextImpl::ContextImpl(InputReader* reader) :
919 mReader(reader) {
920}
921
922void InputReader::ContextImpl::updateGlobalMetaState() {
923 // lock is already held by the input loop
924 mReader->updateGlobalMetaStateLocked();
925}
926
927int32_t InputReader::ContextImpl::getGlobalMetaState() {
928 // lock is already held by the input loop
929 return mReader->getGlobalMetaStateLocked();
930}
931
932void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
933 // lock is already held by the input loop
934 mReader->disableVirtualKeysUntilLocked(time);
935}
936
937bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
938 InputDevice* device, int32_t keyCode, int32_t scanCode) {
939 // lock is already held by the input loop
940 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
941}
942
943void InputReader::ContextImpl::fadePointer() {
944 // lock is already held by the input loop
945 mReader->fadePointerLocked();
946}
947
948void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
949 // lock is already held by the input loop
950 mReader->requestTimeoutAtTimeLocked(when);
951}
952
953int32_t InputReader::ContextImpl::bumpGeneration() {
954 // lock is already held by the input loop
955 return mReader->bumpGenerationLocked();
956}
957
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800958void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700959 // lock is already held by whatever called refreshConfigurationLocked
960 mReader->getExternalStylusDevicesLocked(outDevices);
961}
962
963void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
964 mReader->dispatchExternalStylusState(state);
965}
966
Michael Wrightd02c5b62014-02-10 15:10:22 -0800967InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
968 return mReader->mPolicy.get();
969}
970
971InputListenerInterface* InputReader::ContextImpl::getListener() {
972 return mReader->mQueuedListener.get();
973}
974
975EventHubInterface* InputReader::ContextImpl::getEventHub() {
976 return mReader->mEventHub.get();
977}
978
Prabir Pradhan42611e02018-11-27 14:04:02 -0800979uint32_t InputReader::ContextImpl::getNextSequenceNum() {
980 return (mReader->mNextSequenceNum)++;
981}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982
Michael Wrightd02c5b62014-02-10 15:10:22 -0800983// --- InputDevice ---
984
985InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
986 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
987 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
988 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700989 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990}
991
992InputDevice::~InputDevice() {
993 size_t numMappers = mMappers.size();
994 for (size_t i = 0; i < numMappers; i++) {
995 delete mMappers[i];
996 }
997 mMappers.clear();
998}
999
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001000bool InputDevice::isEnabled() {
1001 return getEventHub()->isDeviceEnabled(mId);
1002}
1003
1004void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1005 if (isEnabled() == enabled) {
1006 return;
1007 }
1008
1009 if (enabled) {
1010 getEventHub()->enableDevice(mId);
1011 reset(when);
1012 } else {
1013 reset(when);
1014 getEventHub()->disableDevice(mId);
1015 }
1016 // Must change generation to flag this device as changed
1017 bumpGeneration();
1018}
1019
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001020void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001022 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001023
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001024 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001025 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001026 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1027 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001028 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1029 if (mAssociatedDisplayPort) {
1030 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1031 } else {
1032 dump += "<none>\n";
1033 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001034 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1035 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1036 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001038 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1039 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001040 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001042 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001043 const char* label = getAxisLabel(range.axis);
1044 char name[32];
1045 if (label) {
1046 strncpy(name, label, sizeof(name));
1047 name[sizeof(name) - 1] = '\0';
1048 } else {
1049 snprintf(name, sizeof(name), "%d", range.axis);
1050 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001051 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001052 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1053 name, range.source, range.min, range.max, range.flat, range.fuzz,
1054 range.resolution);
1055 }
1056 }
1057
1058 size_t numMappers = mMappers.size();
1059 for (size_t i = 0; i < numMappers; i++) {
1060 InputMapper* mapper = mMappers[i];
1061 mapper->dump(dump);
1062 }
1063}
1064
1065void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001066 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001067}
1068
1069void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1070 mSources = 0;
1071
1072 if (!isIgnored()) {
1073 if (!changes) { // first time only
1074 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1075 }
1076
1077 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1078 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1079 sp<KeyCharacterMap> keyboardLayout =
1080 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1081 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1082 bumpGeneration();
1083 }
1084 }
1085 }
1086
1087 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1088 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001089 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001090 if (mAlias != alias) {
1091 mAlias = alias;
1092 bumpGeneration();
1093 }
1094 }
1095 }
1096
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001097 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
Siarhei Vishniakouc6f61192019-07-23 18:12:31 +00001098 auto it = config->disabledDevices.find(mId);
1099 bool enabled = it == config->disabledDevices.end();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001100 setEnabled(enabled, when);
1101 }
1102
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001103 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1104 // In most situations, no port will be specified.
1105 mAssociatedDisplayPort = std::nullopt;
1106 // Find the display port that corresponds to the current input port.
1107 const std::string& inputPort = mIdentifier.location;
1108 if (!inputPort.empty()) {
1109 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1110 const auto& displayPort = ports.find(inputPort);
1111 if (displayPort != ports.end()) {
1112 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1113 }
1114 }
1115 }
1116
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001117 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118 mapper->configure(when, config, changes);
1119 mSources |= mapper->getSources();
1120 }
1121 }
1122}
1123
1124void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001125 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001126 mapper->reset(when);
1127 }
1128
1129 mContext->updateGlobalMetaState();
1130
1131 notifyReset(when);
1132}
1133
1134void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1135 // Process all of the events in order for each mapper.
1136 // We cannot simply ask each mapper to process them in bulk because mappers may
1137 // have side-effects that must be interleaved. For example, joystick movement events and
1138 // gamepad button presses are handled by different mappers but they should be dispatched
1139 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001140 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001142 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1144 rawEvent->when);
1145#endif
1146
1147 if (mDropUntilNextSync) {
1148 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1149 mDropUntilNextSync = false;
1150#if DEBUG_RAW_EVENTS
1151 ALOGD("Recovered from input event buffer overrun.");
1152#endif
1153 } else {
1154#if DEBUG_RAW_EVENTS
1155 ALOGD("Dropped input event while waiting for next input sync.");
1156#endif
1157 }
1158 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001159 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 mDropUntilNextSync = true;
1161 reset(rawEvent->when);
1162 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001163 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 mapper->process(rawEvent);
1165 }
1166 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001167 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 }
1169}
1170
1171void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001172 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001173 mapper->timeoutExpired(when);
1174 }
1175}
1176
Michael Wright842500e2015-03-13 17:32:02 -07001177void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001178 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001179 mapper->updateExternalStylusState(state);
1180 }
1181}
1182
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1184 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001185 mIsExternal, mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001186 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187 mapper->populateDeviceInfo(outDeviceInfo);
1188 }
1189}
1190
1191int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1192 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1193}
1194
1195int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1196 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1197}
1198
1199int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1200 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1201}
1202
1203int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1204 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001205 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1207 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1208 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1209 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1210 if (currentResult >= AKEY_STATE_DOWN) {
1211 return currentResult;
1212 } else if (currentResult == AKEY_STATE_UP) {
1213 result = currentResult;
1214 }
1215 }
1216 }
1217 return result;
1218}
1219
1220bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1221 const int32_t* keyCodes, uint8_t* outFlags) {
1222 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001223 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001224 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1225 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1226 }
1227 }
1228 return result;
1229}
1230
1231void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1232 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001233 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001234 mapper->vibrate(pattern, patternSize, repeat, token);
1235 }
1236}
1237
1238void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001239 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240 mapper->cancelVibrate(token);
1241 }
1242}
1243
Jeff Brownc9aa6282015-02-11 19:03:28 -08001244void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001245 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001246 mapper->cancelTouch(when);
1247 }
1248}
1249
Michael Wrightd02c5b62014-02-10 15:10:22 -08001250int32_t InputDevice::getMetaState() {
1251 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001252 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001253 result |= mapper->getMetaState();
1254 }
1255 return result;
1256}
1257
Andrii Kulian763a3a42016-03-08 10:46:16 -08001258void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001259 for (InputMapper* mapper : mMappers) {
1260 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001261 }
1262}
1263
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001265 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001266 mapper->fadePointer();
1267 }
1268}
1269
1270void InputDevice::bumpGeneration() {
1271 mGeneration = mContext->bumpGeneration();
1272}
1273
1274void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001275 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001276 mContext->getListener()->notifyDeviceReset(&args);
1277}
1278
Arthur Hungc23540e2018-11-29 20:42:11 +08001279std::optional<int32_t> InputDevice::getAssociatedDisplay() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001280 for (InputMapper* mapper : mMappers) {
Arthur Hungc23540e2018-11-29 20:42:11 +08001281 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1282 if (associatedDisplayId) {
1283 return associatedDisplayId;
1284 }
1285 }
1286
1287 return std::nullopt;
1288}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001289
1290// --- CursorButtonAccumulator ---
1291
1292CursorButtonAccumulator::CursorButtonAccumulator() {
1293 clearButtons();
1294}
1295
1296void CursorButtonAccumulator::reset(InputDevice* device) {
1297 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1298 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1299 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1300 mBtnBack = device->isKeyPressed(BTN_BACK);
1301 mBtnSide = device->isKeyPressed(BTN_SIDE);
1302 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1303 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1304 mBtnTask = device->isKeyPressed(BTN_TASK);
1305}
1306
1307void CursorButtonAccumulator::clearButtons() {
1308 mBtnLeft = 0;
1309 mBtnRight = 0;
1310 mBtnMiddle = 0;
1311 mBtnBack = 0;
1312 mBtnSide = 0;
1313 mBtnForward = 0;
1314 mBtnExtra = 0;
1315 mBtnTask = 0;
1316}
1317
1318void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1319 if (rawEvent->type == EV_KEY) {
1320 switch (rawEvent->code) {
1321 case BTN_LEFT:
1322 mBtnLeft = rawEvent->value;
1323 break;
1324 case BTN_RIGHT:
1325 mBtnRight = rawEvent->value;
1326 break;
1327 case BTN_MIDDLE:
1328 mBtnMiddle = rawEvent->value;
1329 break;
1330 case BTN_BACK:
1331 mBtnBack = rawEvent->value;
1332 break;
1333 case BTN_SIDE:
1334 mBtnSide = rawEvent->value;
1335 break;
1336 case BTN_FORWARD:
1337 mBtnForward = rawEvent->value;
1338 break;
1339 case BTN_EXTRA:
1340 mBtnExtra = rawEvent->value;
1341 break;
1342 case BTN_TASK:
1343 mBtnTask = rawEvent->value;
1344 break;
1345 }
1346 }
1347}
1348
1349uint32_t CursorButtonAccumulator::getButtonState() const {
1350 uint32_t result = 0;
1351 if (mBtnLeft) {
1352 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1353 }
1354 if (mBtnRight) {
1355 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1356 }
1357 if (mBtnMiddle) {
1358 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1359 }
1360 if (mBtnBack || mBtnSide) {
1361 result |= AMOTION_EVENT_BUTTON_BACK;
1362 }
1363 if (mBtnForward || mBtnExtra) {
1364 result |= AMOTION_EVENT_BUTTON_FORWARD;
1365 }
1366 return result;
1367}
1368
1369
1370// --- CursorMotionAccumulator ---
1371
1372CursorMotionAccumulator::CursorMotionAccumulator() {
1373 clearRelativeAxes();
1374}
1375
1376void CursorMotionAccumulator::reset(InputDevice* device) {
1377 clearRelativeAxes();
1378}
1379
1380void CursorMotionAccumulator::clearRelativeAxes() {
1381 mRelX = 0;
1382 mRelY = 0;
1383}
1384
1385void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1386 if (rawEvent->type == EV_REL) {
1387 switch (rawEvent->code) {
1388 case REL_X:
1389 mRelX = rawEvent->value;
1390 break;
1391 case REL_Y:
1392 mRelY = rawEvent->value;
1393 break;
1394 }
1395 }
1396}
1397
1398void CursorMotionAccumulator::finishSync() {
1399 clearRelativeAxes();
1400}
1401
1402
1403// --- CursorScrollAccumulator ---
1404
1405CursorScrollAccumulator::CursorScrollAccumulator() :
1406 mHaveRelWheel(false), mHaveRelHWheel(false) {
1407 clearRelativeAxes();
1408}
1409
1410void CursorScrollAccumulator::configure(InputDevice* device) {
1411 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1412 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1413}
1414
1415void CursorScrollAccumulator::reset(InputDevice* device) {
1416 clearRelativeAxes();
1417}
1418
1419void CursorScrollAccumulator::clearRelativeAxes() {
1420 mRelWheel = 0;
1421 mRelHWheel = 0;
1422}
1423
1424void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1425 if (rawEvent->type == EV_REL) {
1426 switch (rawEvent->code) {
1427 case REL_WHEEL:
1428 mRelWheel = rawEvent->value;
1429 break;
1430 case REL_HWHEEL:
1431 mRelHWheel = rawEvent->value;
1432 break;
1433 }
1434 }
1435}
1436
1437void CursorScrollAccumulator::finishSync() {
1438 clearRelativeAxes();
1439}
1440
1441
1442// --- TouchButtonAccumulator ---
1443
1444TouchButtonAccumulator::TouchButtonAccumulator() :
1445 mHaveBtnTouch(false), mHaveStylus(false) {
1446 clearButtons();
1447}
1448
1449void TouchButtonAccumulator::configure(InputDevice* device) {
1450 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1451 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1452 || device->hasKey(BTN_TOOL_RUBBER)
1453 || device->hasKey(BTN_TOOL_BRUSH)
1454 || device->hasKey(BTN_TOOL_PENCIL)
1455 || device->hasKey(BTN_TOOL_AIRBRUSH);
1456}
1457
1458void TouchButtonAccumulator::reset(InputDevice* device) {
1459 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1460 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001461 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1462 mBtnStylus2 =
1463 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001464 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1465 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1466 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1467 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1468 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1469 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1470 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1471 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1472 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1473 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1474 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1475}
1476
1477void TouchButtonAccumulator::clearButtons() {
1478 mBtnTouch = 0;
1479 mBtnStylus = 0;
1480 mBtnStylus2 = 0;
1481 mBtnToolFinger = 0;
1482 mBtnToolPen = 0;
1483 mBtnToolRubber = 0;
1484 mBtnToolBrush = 0;
1485 mBtnToolPencil = 0;
1486 mBtnToolAirbrush = 0;
1487 mBtnToolMouse = 0;
1488 mBtnToolLens = 0;
1489 mBtnToolDoubleTap = 0;
1490 mBtnToolTripleTap = 0;
1491 mBtnToolQuadTap = 0;
1492}
1493
1494void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1495 if (rawEvent->type == EV_KEY) {
1496 switch (rawEvent->code) {
1497 case BTN_TOUCH:
1498 mBtnTouch = rawEvent->value;
1499 break;
1500 case BTN_STYLUS:
1501 mBtnStylus = rawEvent->value;
1502 break;
1503 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001504 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001505 mBtnStylus2 = rawEvent->value;
1506 break;
1507 case BTN_TOOL_FINGER:
1508 mBtnToolFinger = rawEvent->value;
1509 break;
1510 case BTN_TOOL_PEN:
1511 mBtnToolPen = rawEvent->value;
1512 break;
1513 case BTN_TOOL_RUBBER:
1514 mBtnToolRubber = rawEvent->value;
1515 break;
1516 case BTN_TOOL_BRUSH:
1517 mBtnToolBrush = rawEvent->value;
1518 break;
1519 case BTN_TOOL_PENCIL:
1520 mBtnToolPencil = rawEvent->value;
1521 break;
1522 case BTN_TOOL_AIRBRUSH:
1523 mBtnToolAirbrush = rawEvent->value;
1524 break;
1525 case BTN_TOOL_MOUSE:
1526 mBtnToolMouse = rawEvent->value;
1527 break;
1528 case BTN_TOOL_LENS:
1529 mBtnToolLens = rawEvent->value;
1530 break;
1531 case BTN_TOOL_DOUBLETAP:
1532 mBtnToolDoubleTap = rawEvent->value;
1533 break;
1534 case BTN_TOOL_TRIPLETAP:
1535 mBtnToolTripleTap = rawEvent->value;
1536 break;
1537 case BTN_TOOL_QUADTAP:
1538 mBtnToolQuadTap = rawEvent->value;
1539 break;
1540 }
1541 }
1542}
1543
1544uint32_t TouchButtonAccumulator::getButtonState() const {
1545 uint32_t result = 0;
1546 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001547 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001548 }
1549 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001550 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001551 }
1552 return result;
1553}
1554
1555int32_t TouchButtonAccumulator::getToolType() const {
1556 if (mBtnToolMouse || mBtnToolLens) {
1557 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1558 }
1559 if (mBtnToolRubber) {
1560 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1561 }
1562 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1563 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1564 }
1565 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1566 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1567 }
1568 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1569}
1570
1571bool TouchButtonAccumulator::isToolActive() const {
1572 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1573 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1574 || mBtnToolMouse || mBtnToolLens
1575 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1576}
1577
1578bool TouchButtonAccumulator::isHovering() const {
1579 return mHaveBtnTouch && !mBtnTouch;
1580}
1581
1582bool TouchButtonAccumulator::hasStylus() const {
1583 return mHaveStylus;
1584}
1585
1586
1587// --- RawPointerAxes ---
1588
1589RawPointerAxes::RawPointerAxes() {
1590 clear();
1591}
1592
1593void RawPointerAxes::clear() {
1594 x.clear();
1595 y.clear();
1596 pressure.clear();
1597 touchMajor.clear();
1598 touchMinor.clear();
1599 toolMajor.clear();
1600 toolMinor.clear();
1601 orientation.clear();
1602 distance.clear();
1603 tiltX.clear();
1604 tiltY.clear();
1605 trackingId.clear();
1606 slot.clear();
1607}
1608
1609
1610// --- RawPointerData ---
1611
1612RawPointerData::RawPointerData() {
1613 clear();
1614}
1615
1616void RawPointerData::clear() {
1617 pointerCount = 0;
1618 clearIdBits();
1619}
1620
1621void RawPointerData::copyFrom(const RawPointerData& other) {
1622 pointerCount = other.pointerCount;
1623 hoveringIdBits = other.hoveringIdBits;
1624 touchingIdBits = other.touchingIdBits;
1625
1626 for (uint32_t i = 0; i < pointerCount; i++) {
1627 pointers[i] = other.pointers[i];
1628
1629 int id = pointers[i].id;
1630 idToIndex[id] = other.idToIndex[id];
1631 }
1632}
1633
1634void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1635 float x = 0, y = 0;
1636 uint32_t count = touchingIdBits.count();
1637 if (count) {
1638 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1639 uint32_t id = idBits.clearFirstMarkedBit();
1640 const Pointer& pointer = pointerForId(id);
1641 x += pointer.x;
1642 y += pointer.y;
1643 }
1644 x /= count;
1645 y /= count;
1646 }
1647 *outX = x;
1648 *outY = y;
1649}
1650
1651
1652// --- CookedPointerData ---
1653
1654CookedPointerData::CookedPointerData() {
1655 clear();
1656}
1657
1658void CookedPointerData::clear() {
1659 pointerCount = 0;
1660 hoveringIdBits.clear();
1661 touchingIdBits.clear();
1662}
1663
1664void CookedPointerData::copyFrom(const CookedPointerData& other) {
1665 pointerCount = other.pointerCount;
1666 hoveringIdBits = other.hoveringIdBits;
1667 touchingIdBits = other.touchingIdBits;
1668
1669 for (uint32_t i = 0; i < pointerCount; i++) {
1670 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1671 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1672
1673 int id = pointerProperties[i].id;
1674 idToIndex[id] = other.idToIndex[id];
1675 }
1676}
1677
1678
1679// --- SingleTouchMotionAccumulator ---
1680
1681SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1682 clearAbsoluteAxes();
1683}
1684
1685void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1686 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1687 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1688 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1689 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1690 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1691 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1692 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1693}
1694
1695void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1696 mAbsX = 0;
1697 mAbsY = 0;
1698 mAbsPressure = 0;
1699 mAbsToolWidth = 0;
1700 mAbsDistance = 0;
1701 mAbsTiltX = 0;
1702 mAbsTiltY = 0;
1703}
1704
1705void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1706 if (rawEvent->type == EV_ABS) {
1707 switch (rawEvent->code) {
1708 case ABS_X:
1709 mAbsX = rawEvent->value;
1710 break;
1711 case ABS_Y:
1712 mAbsY = rawEvent->value;
1713 break;
1714 case ABS_PRESSURE:
1715 mAbsPressure = rawEvent->value;
1716 break;
1717 case ABS_TOOL_WIDTH:
1718 mAbsToolWidth = rawEvent->value;
1719 break;
1720 case ABS_DISTANCE:
1721 mAbsDistance = rawEvent->value;
1722 break;
1723 case ABS_TILT_X:
1724 mAbsTiltX = rawEvent->value;
1725 break;
1726 case ABS_TILT_Y:
1727 mAbsTiltY = rawEvent->value;
1728 break;
1729 }
1730 }
1731}
1732
1733
1734// --- MultiTouchMotionAccumulator ---
1735
Atif Niyaz21da0ff2019-06-28 13:22:51 -07001736MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1737 : mCurrentSlot(-1),
1738 mSlots(nullptr),
1739 mSlotCount(0),
1740 mUsingSlotsProtocol(false),
1741 mHaveStylus(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001742
1743MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1744 delete[] mSlots;
1745}
1746
1747void MultiTouchMotionAccumulator::configure(InputDevice* device,
1748 size_t slotCount, bool usingSlotsProtocol) {
1749 mSlotCount = slotCount;
1750 mUsingSlotsProtocol = usingSlotsProtocol;
1751 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1752
1753 delete[] mSlots;
1754 mSlots = new Slot[slotCount];
1755}
1756
1757void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1758 // Unfortunately there is no way to read the initial contents of the slots.
1759 // So when we reset the accumulator, we must assume they are all zeroes.
1760 if (mUsingSlotsProtocol) {
1761 // Query the driver for the current slot index and use it as the initial slot
1762 // before we start reading events from the device. It is possible that the
1763 // current slot index will not be the same as it was when the first event was
1764 // written into the evdev buffer, which means the input mapper could start
1765 // out of sync with the initial state of the events in the evdev buffer.
1766 // In the extremely unlikely case that this happens, the data from
1767 // two slots will be confused until the next ABS_MT_SLOT event is received.
1768 // This can cause the touch point to "jump", but at least there will be
1769 // no stuck touches.
1770 int32_t initialSlot;
1771 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1772 ABS_MT_SLOT, &initialSlot);
1773 if (status) {
1774 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1775 initialSlot = -1;
1776 }
1777 clearSlots(initialSlot);
1778 } else {
1779 clearSlots(-1);
1780 }
1781}
1782
1783void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1784 if (mSlots) {
1785 for (size_t i = 0; i < mSlotCount; i++) {
1786 mSlots[i].clear();
1787 }
1788 }
1789 mCurrentSlot = initialSlot;
1790}
1791
1792void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1793 if (rawEvent->type == EV_ABS) {
1794 bool newSlot = false;
1795 if (mUsingSlotsProtocol) {
1796 if (rawEvent->code == ABS_MT_SLOT) {
1797 mCurrentSlot = rawEvent->value;
1798 newSlot = true;
1799 }
1800 } else if (mCurrentSlot < 0) {
1801 mCurrentSlot = 0;
1802 }
1803
1804 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1805#if DEBUG_POINTERS
1806 if (newSlot) {
1807 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001808 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001809 mCurrentSlot, mSlotCount - 1);
1810 }
1811#endif
1812 } else {
1813 Slot* slot = &mSlots[mCurrentSlot];
1814
1815 switch (rawEvent->code) {
1816 case ABS_MT_POSITION_X:
1817 slot->mInUse = true;
1818 slot->mAbsMTPositionX = rawEvent->value;
1819 break;
1820 case ABS_MT_POSITION_Y:
1821 slot->mInUse = true;
1822 slot->mAbsMTPositionY = rawEvent->value;
1823 break;
1824 case ABS_MT_TOUCH_MAJOR:
1825 slot->mInUse = true;
1826 slot->mAbsMTTouchMajor = rawEvent->value;
1827 break;
1828 case ABS_MT_TOUCH_MINOR:
1829 slot->mInUse = true;
1830 slot->mAbsMTTouchMinor = rawEvent->value;
1831 slot->mHaveAbsMTTouchMinor = true;
1832 break;
1833 case ABS_MT_WIDTH_MAJOR:
1834 slot->mInUse = true;
1835 slot->mAbsMTWidthMajor = rawEvent->value;
1836 break;
1837 case ABS_MT_WIDTH_MINOR:
1838 slot->mInUse = true;
1839 slot->mAbsMTWidthMinor = rawEvent->value;
1840 slot->mHaveAbsMTWidthMinor = true;
1841 break;
1842 case ABS_MT_ORIENTATION:
1843 slot->mInUse = true;
1844 slot->mAbsMTOrientation = rawEvent->value;
1845 break;
1846 case ABS_MT_TRACKING_ID:
1847 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1848 // The slot is no longer in use but it retains its previous contents,
1849 // which may be reused for subsequent touches.
1850 slot->mInUse = false;
1851 } else {
1852 slot->mInUse = true;
1853 slot->mAbsMTTrackingId = rawEvent->value;
1854 }
1855 break;
1856 case ABS_MT_PRESSURE:
1857 slot->mInUse = true;
1858 slot->mAbsMTPressure = rawEvent->value;
1859 break;
1860 case ABS_MT_DISTANCE:
1861 slot->mInUse = true;
1862 slot->mAbsMTDistance = rawEvent->value;
1863 break;
1864 case ABS_MT_TOOL_TYPE:
1865 slot->mInUse = true;
1866 slot->mAbsMTToolType = rawEvent->value;
1867 slot->mHaveAbsMTToolType = true;
1868 break;
1869 }
1870 }
1871 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1872 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1873 mCurrentSlot += 1;
1874 }
1875}
1876
1877void MultiTouchMotionAccumulator::finishSync() {
1878 if (!mUsingSlotsProtocol) {
1879 clearSlots(-1);
1880 }
1881}
1882
1883bool MultiTouchMotionAccumulator::hasStylus() const {
1884 return mHaveStylus;
1885}
1886
1887
1888// --- MultiTouchMotionAccumulator::Slot ---
1889
1890MultiTouchMotionAccumulator::Slot::Slot() {
1891 clear();
1892}
1893
1894void MultiTouchMotionAccumulator::Slot::clear() {
1895 mInUse = false;
1896 mHaveAbsMTTouchMinor = false;
1897 mHaveAbsMTWidthMinor = false;
1898 mHaveAbsMTToolType = false;
1899 mAbsMTPositionX = 0;
1900 mAbsMTPositionY = 0;
1901 mAbsMTTouchMajor = 0;
1902 mAbsMTTouchMinor = 0;
1903 mAbsMTWidthMajor = 0;
1904 mAbsMTWidthMinor = 0;
1905 mAbsMTOrientation = 0;
1906 mAbsMTTrackingId = -1;
1907 mAbsMTPressure = 0;
1908 mAbsMTDistance = 0;
1909 mAbsMTToolType = 0;
1910}
1911
1912int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1913 if (mHaveAbsMTToolType) {
1914 switch (mAbsMTToolType) {
1915 case MT_TOOL_FINGER:
1916 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1917 case MT_TOOL_PEN:
1918 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1919 }
1920 }
1921 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1922}
1923
1924
1925// --- InputMapper ---
1926
1927InputMapper::InputMapper(InputDevice* device) :
1928 mDevice(device), mContext(device->getContext()) {
1929}
1930
1931InputMapper::~InputMapper() {
1932}
1933
1934void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1935 info->addSource(getSources());
1936}
1937
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001938void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001939}
1940
1941void InputMapper::configure(nsecs_t when,
1942 const InputReaderConfiguration* config, uint32_t changes) {
1943}
1944
1945void InputMapper::reset(nsecs_t when) {
1946}
1947
1948void InputMapper::timeoutExpired(nsecs_t when) {
1949}
1950
1951int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1952 return AKEY_STATE_UNKNOWN;
1953}
1954
1955int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1956 return AKEY_STATE_UNKNOWN;
1957}
1958
1959int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1960 return AKEY_STATE_UNKNOWN;
1961}
1962
1963bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1964 const int32_t* keyCodes, uint8_t* outFlags) {
1965 return false;
1966}
1967
1968void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1969 int32_t token) {
1970}
1971
1972void InputMapper::cancelVibrate(int32_t token) {
1973}
1974
Jeff Brownc9aa6282015-02-11 19:03:28 -08001975void InputMapper::cancelTouch(nsecs_t when) {
1976}
1977
Michael Wrightd02c5b62014-02-10 15:10:22 -08001978int32_t InputMapper::getMetaState() {
1979 return 0;
1980}
1981
Andrii Kulian763a3a42016-03-08 10:46:16 -08001982void InputMapper::updateMetaState(int32_t keyCode) {
1983}
1984
Michael Wright842500e2015-03-13 17:32:02 -07001985void InputMapper::updateExternalStylusState(const StylusState& state) {
1986
1987}
1988
Michael Wrightd02c5b62014-02-10 15:10:22 -08001989void InputMapper::fadePointer() {
1990}
1991
1992status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1993 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1994}
1995
1996void InputMapper::bumpGeneration() {
1997 mDevice->bumpGeneration();
1998}
1999
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002000void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002001 const RawAbsoluteAxisInfo& axis, const char* name) {
2002 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002003 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2005 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002006 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007 }
2008}
2009
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002010void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2011 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2012 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2013 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2014 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002015}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002016
2017// --- SwitchInputMapper ---
2018
2019SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002020 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002021}
2022
2023SwitchInputMapper::~SwitchInputMapper() {
2024}
2025
2026uint32_t SwitchInputMapper::getSources() {
2027 return AINPUT_SOURCE_SWITCH;
2028}
2029
2030void SwitchInputMapper::process(const RawEvent* rawEvent) {
2031 switch (rawEvent->type) {
2032 case EV_SW:
2033 processSwitch(rawEvent->code, rawEvent->value);
2034 break;
2035
2036 case EV_SYN:
2037 if (rawEvent->code == SYN_REPORT) {
2038 sync(rawEvent->when);
2039 }
2040 }
2041}
2042
2043void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2044 if (switchCode >= 0 && switchCode < 32) {
2045 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002046 mSwitchValues |= 1 << switchCode;
2047 } else {
2048 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 }
2050 mUpdatedSwitchMask |= 1 << switchCode;
2051 }
2052}
2053
2054void SwitchInputMapper::sync(nsecs_t when) {
2055 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002056 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002057 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2058 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 getListener()->notifySwitch(&args);
2060
Michael Wrightd02c5b62014-02-10 15:10:22 -08002061 mUpdatedSwitchMask = 0;
2062 }
2063}
2064
2065int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2066 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2067}
2068
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002069void SwitchInputMapper::dump(std::string& dump) {
2070 dump += INDENT2 "Switch Input Mapper:\n";
2071 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002072}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002073
2074// --- VibratorInputMapper ---
2075
2076VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2077 InputMapper(device), mVibrating(false) {
2078}
2079
2080VibratorInputMapper::~VibratorInputMapper() {
2081}
2082
2083uint32_t VibratorInputMapper::getSources() {
2084 return 0;
2085}
2086
2087void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2088 InputMapper::populateDeviceInfo(info);
2089
2090 info->setVibrator(true);
2091}
2092
2093void VibratorInputMapper::process(const RawEvent* rawEvent) {
2094 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2095}
2096
2097void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2098 int32_t token) {
2099#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002100 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002101 for (size_t i = 0; i < patternSize; i++) {
2102 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002103 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002105 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002106 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002107 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002108 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002109#endif
2110
2111 mVibrating = true;
2112 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2113 mPatternSize = patternSize;
2114 mRepeat = repeat;
2115 mToken = token;
2116 mIndex = -1;
2117
2118 nextStep();
2119}
2120
2121void VibratorInputMapper::cancelVibrate(int32_t token) {
2122#if DEBUG_VIBRATOR
2123 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2124#endif
2125
2126 if (mVibrating && mToken == token) {
2127 stopVibrating();
2128 }
2129}
2130
2131void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2132 if (mVibrating) {
2133 if (when >= mNextStepTime) {
2134 nextStep();
2135 } else {
2136 getContext()->requestTimeoutAtTime(mNextStepTime);
2137 }
2138 }
2139}
2140
2141void VibratorInputMapper::nextStep() {
2142 mIndex += 1;
2143 if (size_t(mIndex) >= mPatternSize) {
2144 if (mRepeat < 0) {
2145 // We are done.
2146 stopVibrating();
2147 return;
2148 }
2149 mIndex = mRepeat;
2150 }
2151
2152 bool vibratorOn = mIndex & 1;
2153 nsecs_t duration = mPattern[mIndex];
2154 if (vibratorOn) {
2155#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002156 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002157#endif
2158 getEventHub()->vibrate(getDeviceId(), duration);
2159 } else {
2160#if DEBUG_VIBRATOR
2161 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2162#endif
2163 getEventHub()->cancelVibrate(getDeviceId());
2164 }
2165 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2166 mNextStepTime = now + duration;
2167 getContext()->requestTimeoutAtTime(mNextStepTime);
2168#if DEBUG_VIBRATOR
2169 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2170#endif
2171}
2172
2173void VibratorInputMapper::stopVibrating() {
2174 mVibrating = false;
2175#if DEBUG_VIBRATOR
2176 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2177#endif
2178 getEventHub()->cancelVibrate(getDeviceId());
2179}
2180
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002181void VibratorInputMapper::dump(std::string& dump) {
2182 dump += INDENT2 "Vibrator Input Mapper:\n";
2183 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002184}
2185
2186
2187// --- KeyboardInputMapper ---
2188
2189KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2190 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002191 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002192}
2193
2194KeyboardInputMapper::~KeyboardInputMapper() {
2195}
2196
2197uint32_t KeyboardInputMapper::getSources() {
2198 return mSource;
2199}
2200
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002201int32_t KeyboardInputMapper::getOrientation() {
2202 if (mViewport) {
2203 return mViewport->orientation;
2204 }
2205 return DISPLAY_ORIENTATION_0;
2206}
2207
2208int32_t KeyboardInputMapper::getDisplayId() {
2209 if (mViewport) {
2210 return mViewport->displayId;
2211 }
2212 return ADISPLAY_ID_NONE;
2213}
2214
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2216 InputMapper::populateDeviceInfo(info);
2217
2218 info->setKeyboardType(mKeyboardType);
2219 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2220}
2221
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002222void KeyboardInputMapper::dump(std::string& dump) {
2223 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002224 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002225 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002226 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002227 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2228 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2229 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230}
2231
Michael Wrightd02c5b62014-02-10 15:10:22 -08002232void KeyboardInputMapper::configure(nsecs_t when,
2233 const InputReaderConfiguration* config, uint32_t changes) {
2234 InputMapper::configure(when, config, changes);
2235
2236 if (!changes) { // first time only
2237 // Configure basic parameters.
2238 configureParameters();
2239 }
2240
2241 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002242 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002243 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 }
2245 }
2246}
2247
Ivan Podogovb9afef32017-02-13 15:34:32 +00002248static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2249 int32_t mapped = 0;
2250 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2251 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2252 if (stemKeyRotationMap[i][0] == keyCode) {
2253 stemKeyRotationMap[i][1] = mapped;
2254 return;
2255 }
2256 }
2257 }
2258}
2259
Michael Wrightd02c5b62014-02-10 15:10:22 -08002260void KeyboardInputMapper::configureParameters() {
2261 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002262 const PropertyMap& config = getDevice()->getConfiguration();
2263 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 mParameters.orientationAware);
2265
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002267 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2268 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2269 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2270 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002272
2273 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002274 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002275 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002276}
2277
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002278void KeyboardInputMapper::dumpParameters(std::string& dump) {
2279 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002280 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002282 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002283 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002284}
2285
2286void KeyboardInputMapper::reset(nsecs_t when) {
2287 mMetaState = AMETA_NONE;
2288 mDownTime = 0;
2289 mKeyDowns.clear();
2290 mCurrentHidUsage = 0;
2291
2292 resetLedState();
2293
2294 InputMapper::reset(when);
2295}
2296
2297void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2298 switch (rawEvent->type) {
2299 case EV_KEY: {
2300 int32_t scanCode = rawEvent->code;
2301 int32_t usageCode = mCurrentHidUsage;
2302 mCurrentHidUsage = 0;
2303
2304 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002305 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002306 }
2307 break;
2308 }
2309 case EV_MSC: {
2310 if (rawEvent->code == MSC_SCAN) {
2311 mCurrentHidUsage = rawEvent->value;
2312 }
2313 break;
2314 }
2315 case EV_SYN: {
2316 if (rawEvent->code == SYN_REPORT) {
2317 mCurrentHidUsage = 0;
2318 }
2319 }
2320 }
2321}
2322
2323bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2324 return scanCode < BTN_MOUSE
2325 || scanCode >= KEY_OK
2326 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2327 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2328}
2329
Michael Wright58ba9882017-07-26 16:19:11 +01002330bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2331 switch (keyCode) {
2332 case AKEYCODE_MEDIA_PLAY:
2333 case AKEYCODE_MEDIA_PAUSE:
2334 case AKEYCODE_MEDIA_PLAY_PAUSE:
2335 case AKEYCODE_MUTE:
2336 case AKEYCODE_HEADSETHOOK:
2337 case AKEYCODE_MEDIA_STOP:
2338 case AKEYCODE_MEDIA_NEXT:
2339 case AKEYCODE_MEDIA_PREVIOUS:
2340 case AKEYCODE_MEDIA_REWIND:
2341 case AKEYCODE_MEDIA_RECORD:
2342 case AKEYCODE_MEDIA_FAST_FORWARD:
2343 case AKEYCODE_MEDIA_SKIP_FORWARD:
2344 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2345 case AKEYCODE_MEDIA_STEP_FORWARD:
2346 case AKEYCODE_MEDIA_STEP_BACKWARD:
2347 case AKEYCODE_MEDIA_AUDIO_TRACK:
2348 case AKEYCODE_VOLUME_UP:
2349 case AKEYCODE_VOLUME_DOWN:
2350 case AKEYCODE_VOLUME_MUTE:
2351 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2352 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2353 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2354 return true;
2355 }
2356 return false;
2357}
2358
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002359void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2360 int32_t usageCode) {
2361 int32_t keyCode;
2362 int32_t keyMetaState;
2363 uint32_t policyFlags;
2364
2365 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2366 &keyCode, &keyMetaState, &policyFlags)) {
2367 keyCode = AKEYCODE_UNKNOWN;
2368 keyMetaState = mMetaState;
2369 policyFlags = 0;
2370 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002371
2372 if (down) {
2373 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002374 if (mParameters.orientationAware) {
2375 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 }
2377
2378 // Add key down.
2379 ssize_t keyDownIndex = findKeyDown(scanCode);
2380 if (keyDownIndex >= 0) {
2381 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002382 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383 } else {
2384 // key down
2385 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2386 && mContext->shouldDropVirtualKey(when,
2387 getDevice(), keyCode, scanCode)) {
2388 return;
2389 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002390 if (policyFlags & POLICY_FLAG_GESTURE) {
2391 mDevice->cancelTouch(when);
2392 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002394 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002395 keyDown.keyCode = keyCode;
2396 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002397 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 }
2399
2400 mDownTime = when;
2401 } else {
2402 // Remove key down.
2403 ssize_t keyDownIndex = findKeyDown(scanCode);
2404 if (keyDownIndex >= 0) {
2405 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002406 keyCode = mKeyDowns[keyDownIndex].keyCode;
2407 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002408 } else {
2409 // key was not actually down
2410 ALOGI("Dropping key up from device %s because the key was not down. "
2411 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002412 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 return;
2414 }
2415 }
2416
Andrii Kulian763a3a42016-03-08 10:46:16 -08002417 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002418 // If global meta state changed send it along with the key.
2419 // If it has not changed then we'll use what keymap gave us,
2420 // since key replacement logic might temporarily reset a few
2421 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002422 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002423 }
2424
2425 nsecs_t downTime = mDownTime;
2426
2427 // Key down on external an keyboard should wake the device.
2428 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2429 // For internal keyboards, the key layout file should specify the policy flags for
2430 // each wake key individually.
2431 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002432 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002433 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002434 }
2435
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002436 if (mParameters.handlesKeyRepeat) {
2437 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2438 }
2439
Prabir Pradhan42611e02018-11-27 14:04:02 -08002440 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2441 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002442 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002443 getListener()->notifyKey(&args);
2444}
2445
2446ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2447 size_t n = mKeyDowns.size();
2448 for (size_t i = 0; i < n; i++) {
2449 if (mKeyDowns[i].scanCode == scanCode) {
2450 return i;
2451 }
2452 }
2453 return -1;
2454}
2455
2456int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2457 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2458}
2459
2460int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2461 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2462}
2463
2464bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2465 const int32_t* keyCodes, uint8_t* outFlags) {
2466 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2467}
2468
2469int32_t KeyboardInputMapper::getMetaState() {
2470 return mMetaState;
2471}
2472
Andrii Kulian763a3a42016-03-08 10:46:16 -08002473void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2474 updateMetaStateIfNeeded(keyCode, false);
2475}
2476
2477bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2478 int32_t oldMetaState = mMetaState;
2479 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2480 bool metaStateChanged = oldMetaState != newMetaState;
2481 if (metaStateChanged) {
2482 mMetaState = newMetaState;
2483 updateLedState(false);
2484
2485 getContext()->updateGlobalMetaState();
2486 }
2487
2488 return metaStateChanged;
2489}
2490
Michael Wrightd02c5b62014-02-10 15:10:22 -08002491void KeyboardInputMapper::resetLedState() {
2492 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2493 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2494 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2495
2496 updateLedState(true);
2497}
2498
2499void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2500 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2501 ledState.on = false;
2502}
2503
2504void KeyboardInputMapper::updateLedState(bool reset) {
2505 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2506 AMETA_CAPS_LOCK_ON, reset);
2507 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2508 AMETA_NUM_LOCK_ON, reset);
2509 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2510 AMETA_SCROLL_LOCK_ON, reset);
2511}
2512
2513void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2514 int32_t led, int32_t modifier, bool reset) {
2515 if (ledState.avail) {
2516 bool desiredState = (mMetaState & modifier) != 0;
2517 if (reset || ledState.on != desiredState) {
2518 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2519 ledState.on = desiredState;
2520 }
2521 }
2522}
2523
2524
2525// --- CursorInputMapper ---
2526
2527CursorInputMapper::CursorInputMapper(InputDevice* device) :
2528 InputMapper(device) {
2529}
2530
2531CursorInputMapper::~CursorInputMapper() {
2532}
2533
2534uint32_t CursorInputMapper::getSources() {
2535 return mSource;
2536}
2537
2538void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2539 InputMapper::populateDeviceInfo(info);
2540
2541 if (mParameters.mode == Parameters::MODE_POINTER) {
2542 float minX, minY, maxX, maxY;
2543 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2544 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2545 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2546 }
2547 } else {
2548 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2549 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2550 }
2551 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2552
2553 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2554 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2555 }
2556 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2557 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2558 }
2559}
2560
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002561void CursorInputMapper::dump(std::string& dump) {
2562 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002563 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002564 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2565 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2566 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2567 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2568 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002570 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002571 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002572 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2573 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2574 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2575 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2576 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2577 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002578}
2579
2580void CursorInputMapper::configure(nsecs_t when,
2581 const InputReaderConfiguration* config, uint32_t changes) {
2582 InputMapper::configure(when, config, changes);
2583
2584 if (!changes) { // first time only
2585 mCursorScrollAccumulator.configure(getDevice());
2586
2587 // Configure basic parameters.
2588 configureParameters();
2589
2590 // Configure device mode.
2591 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002592 case Parameters::MODE_POINTER_RELATIVE:
2593 // Should not happen during first time configuration.
2594 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2595 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002596 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 case Parameters::MODE_POINTER:
2598 mSource = AINPUT_SOURCE_MOUSE;
2599 mXPrecision = 1.0f;
2600 mYPrecision = 1.0f;
2601 mXScale = 1.0f;
2602 mYScale = 1.0f;
2603 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2604 break;
2605 case Parameters::MODE_NAVIGATION:
2606 mSource = AINPUT_SOURCE_TRACKBALL;
2607 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2608 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2609 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2610 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2611 break;
2612 }
2613
2614 mVWheelScale = 1.0f;
2615 mHWheelScale = 1.0f;
2616 }
2617
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002618 if ((!changes && config->pointerCapture)
2619 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2620 if (config->pointerCapture) {
2621 if (mParameters.mode == Parameters::MODE_POINTER) {
2622 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2623 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2624 // Keep PointerController around in order to preserve the pointer position.
2625 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2626 } else {
2627 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2628 }
2629 } else {
2630 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2631 mParameters.mode = Parameters::MODE_POINTER;
2632 mSource = AINPUT_SOURCE_MOUSE;
2633 } else {
2634 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2635 }
2636 }
2637 bumpGeneration();
2638 if (changes) {
2639 getDevice()->notifyReset(when);
2640 }
2641 }
2642
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2644 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2645 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2646 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2647 }
2648
2649 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002650 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002651 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002652 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002653 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002654 if (internalViewport) {
2655 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002658
2659 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002660 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002661 getPolicy()->obtainPointerController(getDeviceId());
2662 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002663 bumpGeneration();
2664 }
2665}
2666
2667void CursorInputMapper::configureParameters() {
2668 mParameters.mode = Parameters::MODE_POINTER;
2669 String8 cursorModeString;
2670 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2671 if (cursorModeString == "navigation") {
2672 mParameters.mode = Parameters::MODE_NAVIGATION;
2673 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2674 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2675 }
2676 }
2677
2678 mParameters.orientationAware = false;
2679 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2680 mParameters.orientationAware);
2681
2682 mParameters.hasAssociatedDisplay = false;
2683 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2684 mParameters.hasAssociatedDisplay = true;
2685 }
2686}
2687
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002688void CursorInputMapper::dumpParameters(std::string& dump) {
2689 dump += INDENT3 "Parameters:\n";
2690 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 toString(mParameters.hasAssociatedDisplay));
2692
2693 switch (mParameters.mode) {
2694 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002695 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002696 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002697 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002698 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002699 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002701 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002702 break;
2703 default:
2704 ALOG_ASSERT(false);
2705 }
2706
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002707 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002708 toString(mParameters.orientationAware));
2709}
2710
2711void CursorInputMapper::reset(nsecs_t when) {
2712 mButtonState = 0;
2713 mDownTime = 0;
2714
2715 mPointerVelocityControl.reset();
2716 mWheelXVelocityControl.reset();
2717 mWheelYVelocityControl.reset();
2718
2719 mCursorButtonAccumulator.reset(getDevice());
2720 mCursorMotionAccumulator.reset(getDevice());
2721 mCursorScrollAccumulator.reset(getDevice());
2722
2723 InputMapper::reset(when);
2724}
2725
2726void CursorInputMapper::process(const RawEvent* rawEvent) {
2727 mCursorButtonAccumulator.process(rawEvent);
2728 mCursorMotionAccumulator.process(rawEvent);
2729 mCursorScrollAccumulator.process(rawEvent);
2730
2731 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2732 sync(rawEvent->when);
2733 }
2734}
2735
2736void CursorInputMapper::sync(nsecs_t when) {
2737 int32_t lastButtonState = mButtonState;
2738 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2739 mButtonState = currentButtonState;
2740
2741 bool wasDown = isPointerDown(lastButtonState);
2742 bool down = isPointerDown(currentButtonState);
2743 bool downChanged;
2744 if (!wasDown && down) {
2745 mDownTime = when;
2746 downChanged = true;
2747 } else if (wasDown && !down) {
2748 downChanged = true;
2749 } else {
2750 downChanged = false;
2751 }
2752 nsecs_t downTime = mDownTime;
2753 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002754 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2755 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002756
2757 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2758 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2759 bool moved = deltaX != 0 || deltaY != 0;
2760
2761 // Rotate delta according to orientation if needed.
2762 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2763 && (deltaX != 0.0f || deltaY != 0.0f)) {
2764 rotateDelta(mOrientation, &deltaX, &deltaY);
2765 }
2766
2767 // Move the pointer.
2768 PointerProperties pointerProperties;
2769 pointerProperties.clear();
2770 pointerProperties.id = 0;
2771 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2772
2773 PointerCoords pointerCoords;
2774 pointerCoords.clear();
2775
2776 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2777 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2778 bool scrolled = vscroll != 0 || hscroll != 0;
2779
Yi Kong9b14ac62018-07-17 13:48:38 -07002780 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2781 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
2783 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2784
2785 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002786 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2787 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002788 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002789 if (moved || scrolled || buttonsChanged) {
2790 mPointerController->setPresentation(
2791 PointerControllerInterface::PRESENTATION_POINTER);
2792
2793 if (moved) {
2794 mPointerController->move(deltaX, deltaY);
2795 }
2796
2797 if (buttonsChanged) {
2798 mPointerController->setButtonState(currentButtonState);
2799 }
2800
2801 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2802 }
2803
Garfield Tan00f511d2019-06-12 16:55:40 -07002804 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002807 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2808 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002809 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 } else {
2811 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2812 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2813 displayId = ADISPLAY_ID_NONE;
2814 }
2815
2816 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2817
2818 // Moving an external trackball or mouse should wake the device.
2819 // We don't do this for internal cursor devices to prevent them from waking up
2820 // the device in your pocket.
2821 // TODO: Use the input device configuration to control this behavior more finely.
2822 uint32_t policyFlags = 0;
2823 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002824 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002825 }
2826
2827 // Synthesize key down from buttons if needed.
2828 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002829 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002830
2831 // Send motion event.
2832 if (downChanged || moved || scrolled || buttonsChanged) {
2833 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002834 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 int32_t motionEventAction;
2836 if (downChanged) {
2837 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002838 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2840 } else {
2841 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2842 }
2843
Michael Wright7b159c92015-05-14 14:48:03 +01002844 if (buttonsReleased) {
2845 BitSet32 released(buttonsReleased);
2846 while (!released.isEmpty()) {
2847 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2848 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002849 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002850 mSource, displayId, policyFlags,
2851 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2852 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002853 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002854 &pointerCoords, mXPrecision, mYPrecision,
2855 xCursorPosition, yCursorPosition, downTime,
2856 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002857 getListener()->notifyMotion(&releaseArgs);
2858 }
2859 }
2860
Prabir Pradhan42611e02018-11-27 14:04:02 -08002861 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Garfield Tan00f511d2019-06-12 16:55:40 -07002862 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2863 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002864 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
Garfield Tan00f511d2019-06-12 16:55:40 -07002865 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2866 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 getListener()->notifyMotion(&args);
2868
Michael Wright7b159c92015-05-14 14:48:03 +01002869 if (buttonsPressed) {
2870 BitSet32 pressed(buttonsPressed);
2871 while (!pressed.isEmpty()) {
2872 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2873 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002874 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002875 mSource, displayId, policyFlags,
2876 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2877 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002878 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002879 &pointerCoords, mXPrecision, mYPrecision,
2880 xCursorPosition, yCursorPosition, downTime,
2881 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002882 getListener()->notifyMotion(&pressArgs);
2883 }
2884 }
2885
2886 ALOG_ASSERT(buttonState == currentButtonState);
2887
Michael Wrightd02c5b62014-02-10 15:10:22 -08002888 // Send hover move after UP to tell the application that the mouse is hovering now.
2889 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002890 && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002891 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2892 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2893 0, metaState, currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002894 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002895 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002896 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002897 getListener()->notifyMotion(&hoverArgs);
2898 }
2899
2900 // Send scroll events.
2901 if (scrolled) {
2902 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2903 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2904
Prabir Pradhan42611e02018-11-27 14:04:02 -08002905 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002906 mSource, displayId, policyFlags,
2907 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2908 currentButtonState, 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, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002911 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912 getListener()->notifyMotion(&scrollArgs);
2913 }
2914 }
2915
2916 // Synthesize key up from buttons if needed.
2917 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002918 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002919
2920 mCursorMotionAccumulator.finishSync();
2921 mCursorScrollAccumulator.finishSync();
2922}
2923
2924int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2925 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2926 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2927 } else {
2928 return AKEY_STATE_UNKNOWN;
2929 }
2930}
2931
2932void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002933 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002934 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2935 }
2936}
2937
Arthur Hungc23540e2018-11-29 20:42:11 +08002938std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2939 if (mParameters.hasAssociatedDisplay) {
2940 if (mParameters.mode == Parameters::MODE_POINTER) {
2941 return std::make_optional(mPointerController->getDisplayId());
2942 } else {
2943 // If the device is orientationAware and not a mouse,
2944 // it expects to dispatch events to any display
2945 return std::make_optional(ADISPLAY_ID_NONE);
2946 }
2947 }
2948 return std::nullopt;
2949}
2950
Prashant Malani1941ff52015-08-11 18:29:28 -07002951// --- RotaryEncoderInputMapper ---
2952
2953RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002954 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002955 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2956}
2957
2958RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2959}
2960
2961uint32_t RotaryEncoderInputMapper::getSources() {
2962 return mSource;
2963}
2964
2965void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2966 InputMapper::populateDeviceInfo(info);
2967
2968 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002969 float res = 0.0f;
2970 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2971 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2972 }
2973 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2974 mScalingFactor)) {
2975 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2976 "default to 1.0!\n");
2977 mScalingFactor = 1.0f;
2978 }
2979 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2980 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002981 }
2982}
2983
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002984void RotaryEncoderInputMapper::dump(std::string& dump) {
2985 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2986 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002987 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2988}
2989
2990void RotaryEncoderInputMapper::configure(nsecs_t when,
2991 const InputReaderConfiguration* config, uint32_t changes) {
2992 InputMapper::configure(when, config, changes);
2993 if (!changes) {
2994 mRotaryEncoderScrollAccumulator.configure(getDevice());
2995 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002996 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002997 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002998 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002999 if (internalViewport) {
3000 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003001 } else {
3002 mOrientation = DISPLAY_ORIENTATION_0;
3003 }
3004 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003005}
3006
3007void RotaryEncoderInputMapper::reset(nsecs_t when) {
3008 mRotaryEncoderScrollAccumulator.reset(getDevice());
3009
3010 InputMapper::reset(when);
3011}
3012
3013void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3014 mRotaryEncoderScrollAccumulator.process(rawEvent);
3015
3016 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3017 sync(rawEvent->when);
3018 }
3019}
3020
3021void RotaryEncoderInputMapper::sync(nsecs_t when) {
3022 PointerCoords pointerCoords;
3023 pointerCoords.clear();
3024
3025 PointerProperties pointerProperties;
3026 pointerProperties.clear();
3027 pointerProperties.id = 0;
3028 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3029
3030 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3031 bool scrolled = scroll != 0;
3032
3033 // This is not a pointer, so it's not associated with a display.
3034 int32_t displayId = ADISPLAY_ID_NONE;
3035
3036 // Moving the rotary encoder should wake the device (if specified).
3037 uint32_t policyFlags = 0;
3038 if (scrolled && getDevice()->isExternal()) {
3039 policyFlags |= POLICY_FLAG_WAKE;
3040 }
3041
Ivan Podogovad437252016-09-29 16:29:55 +01003042 if (mOrientation == DISPLAY_ORIENTATION_180) {
3043 scroll = -scroll;
3044 }
3045
Prashant Malani1941ff52015-08-11 18:29:28 -07003046 // Send motion event.
3047 if (scrolled) {
3048 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003049 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003050
Garfield Tan00f511d2019-06-12 16:55:40 -07003051 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3052 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3053 metaState, /* buttonState */ 0, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07003054 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
3055 &pointerCoords, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Garfield Tan00f511d2019-06-12 16:55:40 -07003056 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003057 getListener()->notifyMotion(&scrollArgs);
3058 }
3059
3060 mRotaryEncoderScrollAccumulator.finishSync();
3061}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003062
3063// --- TouchInputMapper ---
3064
3065TouchInputMapper::TouchInputMapper(InputDevice* device) :
3066 InputMapper(device),
3067 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3068 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003069 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003070 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3071}
3072
3073TouchInputMapper::~TouchInputMapper() {
3074}
3075
3076uint32_t TouchInputMapper::getSources() {
3077 return mSource;
3078}
3079
3080void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3081 InputMapper::populateDeviceInfo(info);
3082
3083 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3084 info->addMotionRange(mOrientedRanges.x);
3085 info->addMotionRange(mOrientedRanges.y);
3086 info->addMotionRange(mOrientedRanges.pressure);
3087
3088 if (mOrientedRanges.haveSize) {
3089 info->addMotionRange(mOrientedRanges.size);
3090 }
3091
3092 if (mOrientedRanges.haveTouchSize) {
3093 info->addMotionRange(mOrientedRanges.touchMajor);
3094 info->addMotionRange(mOrientedRanges.touchMinor);
3095 }
3096
3097 if (mOrientedRanges.haveToolSize) {
3098 info->addMotionRange(mOrientedRanges.toolMajor);
3099 info->addMotionRange(mOrientedRanges.toolMinor);
3100 }
3101
3102 if (mOrientedRanges.haveOrientation) {
3103 info->addMotionRange(mOrientedRanges.orientation);
3104 }
3105
3106 if (mOrientedRanges.haveDistance) {
3107 info->addMotionRange(mOrientedRanges.distance);
3108 }
3109
3110 if (mOrientedRanges.haveTilt) {
3111 info->addMotionRange(mOrientedRanges.tilt);
3112 }
3113
3114 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3115 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3116 0.0f);
3117 }
3118 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3119 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3120 0.0f);
3121 }
3122 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3123 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3124 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3125 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3126 x.fuzz, x.resolution);
3127 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3128 y.fuzz, y.resolution);
3129 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3130 x.fuzz, x.resolution);
3131 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3132 y.fuzz, y.resolution);
3133 }
3134 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3135 }
3136}
3137
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003138void TouchInputMapper::dump(std::string& dump) {
3139 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003140 dumpParameters(dump);
3141 dumpVirtualKeys(dump);
3142 dumpRawPointerAxes(dump);
3143 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003144 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003145 dumpSurface(dump);
3146
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003147 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3148 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3149 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3150 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3151 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3152 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3153 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3154 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3155 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3156 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3157 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3158 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3159 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3160 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3161 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3162 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3163 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003165 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3166 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003167 mLastRawState.rawPointerData.pointerCount);
3168 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3169 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3172 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3173 "toolType=%d, isHovering=%s\n", i,
3174 pointer.id, pointer.x, pointer.y, pointer.pressure,
3175 pointer.touchMajor, pointer.touchMinor,
3176 pointer.toolMajor, pointer.toolMinor,
3177 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3178 pointer.toolType, toString(pointer.isHovering));
3179 }
3180
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3182 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003183 mLastCookedState.cookedPointerData.pointerCount);
3184 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3185 const PointerProperties& pointerProperties =
3186 mLastCookedState.cookedPointerData.pointerProperties[i];
3187 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003189 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3190 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3191 "toolType=%d, isHovering=%s\n", i,
3192 pointerProperties.id,
3193 pointerCoords.getX(),
3194 pointerCoords.getY(),
3195 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3196 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3197 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3198 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3199 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3200 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3201 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3202 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3203 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003204 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003205 }
3206
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003207 dump += INDENT3 "Stylus Fusion:\n";
3208 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003209 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003210 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3211 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003212 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003213 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003214 dumpStylusState(dump, mExternalStylusState);
3215
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3218 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003222 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003224 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 mPointerGestureMaxSwipeWidth);
3228 }
3229}
3230
Santos Cordonfa5cf462017-04-05 10:37:00 -07003231const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3232 switch (deviceMode) {
3233 case DEVICE_MODE_DISABLED:
3234 return "disabled";
3235 case DEVICE_MODE_DIRECT:
3236 return "direct";
3237 case DEVICE_MODE_UNSCALED:
3238 return "unscaled";
3239 case DEVICE_MODE_NAVIGATION:
3240 return "navigation";
3241 case DEVICE_MODE_POINTER:
3242 return "pointer";
3243 }
3244 return "unknown";
3245}
3246
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247void TouchInputMapper::configure(nsecs_t when,
3248 const InputReaderConfiguration* config, uint32_t changes) {
3249 InputMapper::configure(when, config, changes);
3250
3251 mConfig = *config;
3252
3253 if (!changes) { // first time only
3254 // Configure basic parameters.
3255 configureParameters();
3256
3257 // Configure common accumulators.
3258 mCursorScrollAccumulator.configure(getDevice());
3259 mTouchButtonAccumulator.configure(getDevice());
3260
3261 // Configure absolute axis information.
3262 configureRawPointerAxes();
3263
3264 // Prepare input device calibration.
3265 parseCalibration();
3266 resolveCalibration();
3267 }
3268
Michael Wright842500e2015-03-13 17:32:02 -07003269 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003270 // Update location calibration to reflect current settings
3271 updateAffineTransformation();
3272 }
3273
Michael Wrightd02c5b62014-02-10 15:10:22 -08003274 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3275 // Update pointer speed.
3276 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3277 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3278 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3279 }
3280
3281 bool resetNeeded = false;
3282 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3283 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003284 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3285 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003286 // Configure device sources, surface dimensions, orientation and
3287 // scaling factors.
3288 configureSurface(when, &resetNeeded);
3289 }
3290
3291 if (changes && resetNeeded) {
3292 // Send reset, unless this is the first time the device has been configured,
3293 // in which case the reader will call reset itself after all mappers are ready.
3294 getDevice()->notifyReset(when);
3295 }
3296}
3297
Michael Wright842500e2015-03-13 17:32:02 -07003298void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003299 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003300 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003301 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003302
3303 if (!mExternalStylusConnected) {
3304 resetExternalStylus();
3305 }
3306}
3307
Michael Wrightd02c5b62014-02-10 15:10:22 -08003308void TouchInputMapper::configureParameters() {
3309 // Use the pointer presentation mode for devices that do not support distinct
3310 // multitouch. The spot-based presentation relies on being able to accurately
3311 // locate two or more fingers on the touch pad.
3312 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003313 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003314
3315 String8 gestureModeString;
3316 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3317 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003318 if (gestureModeString == "single-touch") {
3319 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3320 } else if (gestureModeString == "multi-touch") {
3321 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003322 } else if (gestureModeString != "default") {
3323 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3324 }
3325 }
3326
3327 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3328 // The device is a touch screen.
3329 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3330 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3331 // The device is a pointing device like a track pad.
3332 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3333 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3334 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3335 // The device is a cursor device with a touch pad attached.
3336 // By default don't use the touch pad to move the pointer.
3337 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3338 } else {
3339 // The device is a touch pad of unknown purpose.
3340 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3341 }
3342
3343 mParameters.hasButtonUnderPad=
3344 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3345
3346 String8 deviceTypeString;
3347 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3348 deviceTypeString)) {
3349 if (deviceTypeString == "touchScreen") {
3350 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3351 } else if (deviceTypeString == "touchPad") {
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3353 } else if (deviceTypeString == "touchNavigation") {
3354 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3355 } else if (deviceTypeString == "pointer") {
3356 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3357 } else if (deviceTypeString != "default") {
3358 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3359 }
3360 }
3361
3362 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3363 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3364 mParameters.orientationAware);
3365
3366 mParameters.hasAssociatedDisplay = false;
3367 mParameters.associatedDisplayIsExternal = false;
3368 if (mParameters.orientationAware
3369 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3370 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3371 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003372 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3373 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003374 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003375 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003376 uniqueDisplayId);
3377 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003380 if (getDevice()->getAssociatedDisplayPort()) {
3381 mParameters.hasAssociatedDisplay = true;
3382 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003383
3384 // Initial downs on external touch devices should wake the device.
3385 // Normally we don't do this for internal touch screens to prevent them from waking
3386 // up in your pocket but you can enable it using the input device configuration.
3387 mParameters.wake = getDevice()->isExternal();
3388 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3389 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390}
3391
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003392void TouchInputMapper::dumpParameters(std::string& dump) {
3393 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394
3395 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003396 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003397 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003399 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003400 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401 break;
3402 default:
3403 assert(false);
3404 }
3405
3406 switch (mParameters.deviceType) {
3407 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003408 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 break;
3410 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003411 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003412 break;
3413 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003414 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 break;
3416 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003417 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 break;
3419 default:
3420 ALOG_ASSERT(false);
3421 }
3422
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003423 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003424 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003426 toString(mParameters.associatedDisplayIsExternal),
3427 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003428 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 toString(mParameters.orientationAware));
3430}
3431
3432void TouchInputMapper::configureRawPointerAxes() {
3433 mRawPointerAxes.clear();
3434}
3435
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003436void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3437 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3439 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3440 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3441 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3444 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3445 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3446 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3447 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3451}
3452
Michael Wright842500e2015-03-13 17:32:02 -07003453bool TouchInputMapper::hasExternalStylus() const {
3454 return mExternalStylusConnected;
3455}
3456
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003457/**
3458 * Determine which DisplayViewport to use.
3459 * 1. If display port is specified, return the matching viewport. If matching viewport not
3460 * found, then return.
3461 * 2. If a device has associated display, get the matching viewport by either unique id or by
3462 * the display type (internal or external).
3463 * 3. Otherwise, use a non-display viewport.
3464 */
3465std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3466 if (mParameters.hasAssociatedDisplay) {
3467 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3468 if (displayPort) {
3469 // Find the viewport that contains the same port
3470 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3471 if (!v) {
3472 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3473 "but the corresponding viewport is not found.",
3474 getDeviceName().c_str(), *displayPort);
3475 }
3476 return v;
3477 }
3478
3479 if (!mParameters.uniqueDisplayId.empty()) {
3480 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3481 }
3482
3483 ViewportType viewportTypeToUse;
3484 if (mParameters.associatedDisplayIsExternal) {
3485 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3486 } else {
3487 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3488 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003489
3490 std::optional<DisplayViewport> viewport =
3491 mConfig.getDisplayViewportByType(viewportTypeToUse);
3492 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3493 ALOGW("Input device %s should be associated with external display, "
3494 "fallback to internal one for the external viewport is not found.",
3495 getDeviceName().c_str());
3496 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3497 }
3498
3499 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003500 }
3501
3502 DisplayViewport newViewport;
3503 // Raw width and height in the natural orientation.
3504 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3505 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3506 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3507 return std::make_optional(newViewport);
3508}
3509
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3511 int32_t oldDeviceMode = mDeviceMode;
3512
Michael Wright842500e2015-03-13 17:32:02 -07003513 resolveExternalStylusPresence();
3514
Michael Wrightd02c5b62014-02-10 15:10:22 -08003515 // Determine device mode.
3516 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3517 && mConfig.pointerGesturesEnabled) {
3518 mSource = AINPUT_SOURCE_MOUSE;
3519 mDeviceMode = DEVICE_MODE_POINTER;
3520 if (hasStylus()) {
3521 mSource |= AINPUT_SOURCE_STYLUS;
3522 }
3523 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3524 && mParameters.hasAssociatedDisplay) {
3525 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3526 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003527 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003528 mSource |= AINPUT_SOURCE_STYLUS;
3529 }
Michael Wright2f78b682015-06-12 15:25:08 +01003530 if (hasExternalStylus()) {
3531 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3532 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003533 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3534 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3535 mDeviceMode = DEVICE_MODE_NAVIGATION;
3536 } else {
3537 mSource = AINPUT_SOURCE_TOUCHPAD;
3538 mDeviceMode = DEVICE_MODE_UNSCALED;
3539 }
3540
3541 // Ensure we have valid X and Y axes.
3542 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003543 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003544 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003545 mDeviceMode = DEVICE_MODE_DISABLED;
3546 return;
3547 }
3548
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003549 // Get associated display dimensions.
3550 std::optional<DisplayViewport> newViewport = findViewport();
3551 if (!newViewport) {
3552 ALOGI("Touch device '%s' could not query the properties of its associated "
3553 "display. The device will be inoperable until the display size "
3554 "becomes available.",
3555 getDeviceName().c_str());
3556 mDeviceMode = DEVICE_MODE_DISABLED;
3557 return;
3558 }
3559
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003561 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3562 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003564 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003566 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567
3568 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3569 // Convert rotated viewport to natural surface coordinates.
3570 int32_t naturalLogicalWidth, naturalLogicalHeight;
3571 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3572 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3573 int32_t naturalDeviceWidth, naturalDeviceHeight;
3574 switch (mViewport.orientation) {
3575 case DISPLAY_ORIENTATION_90:
3576 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3577 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3578 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3579 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3580 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3581 naturalPhysicalTop = mViewport.physicalLeft;
3582 naturalDeviceWidth = mViewport.deviceHeight;
3583 naturalDeviceHeight = mViewport.deviceWidth;
3584 break;
3585 case DISPLAY_ORIENTATION_180:
3586 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3587 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3588 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3589 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3590 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3591 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3592 naturalDeviceWidth = mViewport.deviceWidth;
3593 naturalDeviceHeight = mViewport.deviceHeight;
3594 break;
3595 case DISPLAY_ORIENTATION_270:
3596 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3597 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3598 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3599 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3600 naturalPhysicalLeft = mViewport.physicalTop;
3601 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3602 naturalDeviceWidth = mViewport.deviceHeight;
3603 naturalDeviceHeight = mViewport.deviceWidth;
3604 break;
3605 case DISPLAY_ORIENTATION_0:
3606 default:
3607 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3608 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3609 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3610 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3611 naturalPhysicalLeft = mViewport.physicalLeft;
3612 naturalPhysicalTop = mViewport.physicalTop;
3613 naturalDeviceWidth = mViewport.deviceWidth;
3614 naturalDeviceHeight = mViewport.deviceHeight;
3615 break;
3616 }
3617
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003618 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3619 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3620 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3621 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3622 }
3623
Michael Wright358bcc72018-08-21 04:01:07 +01003624 mPhysicalWidth = naturalPhysicalWidth;
3625 mPhysicalHeight = naturalPhysicalHeight;
3626 mPhysicalLeft = naturalPhysicalLeft;
3627 mPhysicalTop = naturalPhysicalTop;
3628
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3630 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3631 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3632 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3633
3634 mSurfaceOrientation = mParameters.orientationAware ?
3635 mViewport.orientation : DISPLAY_ORIENTATION_0;
3636 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003637 mPhysicalWidth = rawWidth;
3638 mPhysicalHeight = rawHeight;
3639 mPhysicalLeft = 0;
3640 mPhysicalTop = 0;
3641
Michael Wrightd02c5b62014-02-10 15:10:22 -08003642 mSurfaceWidth = rawWidth;
3643 mSurfaceHeight = rawHeight;
3644 mSurfaceLeft = 0;
3645 mSurfaceTop = 0;
3646 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3647 }
3648 }
3649
3650 // If moving between pointer modes, need to reset some state.
3651 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3652 if (deviceModeChanged) {
3653 mOrientedRanges.clear();
3654 }
3655
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003656 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003657 if (mDeviceMode == DEVICE_MODE_POINTER ||
3658 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003659 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3661 }
3662 } else {
3663 mPointerController.clear();
3664 }
3665
3666 if (viewportChanged || deviceModeChanged) {
3667 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3668 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003669 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003670 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3671
3672 // Configure X and Y factors.
3673 mXScale = float(mSurfaceWidth) / rawWidth;
3674 mYScale = float(mSurfaceHeight) / rawHeight;
3675 mXTranslate = -mSurfaceLeft;
3676 mYTranslate = -mSurfaceTop;
3677 mXPrecision = 1.0f / mXScale;
3678 mYPrecision = 1.0f / mYScale;
3679
3680 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3681 mOrientedRanges.x.source = mSource;
3682 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3683 mOrientedRanges.y.source = mSource;
3684
3685 configureVirtualKeys();
3686
3687 // Scale factor for terms that are not oriented in a particular axis.
3688 // If the pixels are square then xScale == yScale otherwise we fake it
3689 // by choosing an average.
3690 mGeometricScale = avg(mXScale, mYScale);
3691
3692 // Size of diagonal axis.
3693 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3694
3695 // Size factors.
3696 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3697 if (mRawPointerAxes.touchMajor.valid
3698 && mRawPointerAxes.touchMajor.maxValue != 0) {
3699 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3700 } else if (mRawPointerAxes.toolMajor.valid
3701 && mRawPointerAxes.toolMajor.maxValue != 0) {
3702 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3703 } else {
3704 mSizeScale = 0.0f;
3705 }
3706
3707 mOrientedRanges.haveTouchSize = true;
3708 mOrientedRanges.haveToolSize = true;
3709 mOrientedRanges.haveSize = true;
3710
3711 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3712 mOrientedRanges.touchMajor.source = mSource;
3713 mOrientedRanges.touchMajor.min = 0;
3714 mOrientedRanges.touchMajor.max = diagonalSize;
3715 mOrientedRanges.touchMajor.flat = 0;
3716 mOrientedRanges.touchMajor.fuzz = 0;
3717 mOrientedRanges.touchMajor.resolution = 0;
3718
3719 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3720 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3721
3722 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3723 mOrientedRanges.toolMajor.source = mSource;
3724 mOrientedRanges.toolMajor.min = 0;
3725 mOrientedRanges.toolMajor.max = diagonalSize;
3726 mOrientedRanges.toolMajor.flat = 0;
3727 mOrientedRanges.toolMajor.fuzz = 0;
3728 mOrientedRanges.toolMajor.resolution = 0;
3729
3730 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3731 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3732
3733 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3734 mOrientedRanges.size.source = mSource;
3735 mOrientedRanges.size.min = 0;
3736 mOrientedRanges.size.max = 1.0;
3737 mOrientedRanges.size.flat = 0;
3738 mOrientedRanges.size.fuzz = 0;
3739 mOrientedRanges.size.resolution = 0;
3740 } else {
3741 mSizeScale = 0.0f;
3742 }
3743
3744 // Pressure factors.
3745 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003746 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003747 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3748 || mCalibration.pressureCalibration
3749 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3750 if (mCalibration.havePressureScale) {
3751 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003752 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003753 } else if (mRawPointerAxes.pressure.valid
3754 && mRawPointerAxes.pressure.maxValue != 0) {
3755 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3756 }
3757 }
3758
3759 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3760 mOrientedRanges.pressure.source = mSource;
3761 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003762 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003763 mOrientedRanges.pressure.flat = 0;
3764 mOrientedRanges.pressure.fuzz = 0;
3765 mOrientedRanges.pressure.resolution = 0;
3766
3767 // Tilt
3768 mTiltXCenter = 0;
3769 mTiltXScale = 0;
3770 mTiltYCenter = 0;
3771 mTiltYScale = 0;
3772 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3773 if (mHaveTilt) {
3774 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3775 mRawPointerAxes.tiltX.maxValue);
3776 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3777 mRawPointerAxes.tiltY.maxValue);
3778 mTiltXScale = M_PI / 180;
3779 mTiltYScale = M_PI / 180;
3780
3781 mOrientedRanges.haveTilt = true;
3782
3783 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3784 mOrientedRanges.tilt.source = mSource;
3785 mOrientedRanges.tilt.min = 0;
3786 mOrientedRanges.tilt.max = M_PI_2;
3787 mOrientedRanges.tilt.flat = 0;
3788 mOrientedRanges.tilt.fuzz = 0;
3789 mOrientedRanges.tilt.resolution = 0;
3790 }
3791
3792 // Orientation
3793 mOrientationScale = 0;
3794 if (mHaveTilt) {
3795 mOrientedRanges.haveOrientation = true;
3796
3797 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3798 mOrientedRanges.orientation.source = mSource;
3799 mOrientedRanges.orientation.min = -M_PI;
3800 mOrientedRanges.orientation.max = M_PI;
3801 mOrientedRanges.orientation.flat = 0;
3802 mOrientedRanges.orientation.fuzz = 0;
3803 mOrientedRanges.orientation.resolution = 0;
3804 } else if (mCalibration.orientationCalibration !=
3805 Calibration::ORIENTATION_CALIBRATION_NONE) {
3806 if (mCalibration.orientationCalibration
3807 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3808 if (mRawPointerAxes.orientation.valid) {
3809 if (mRawPointerAxes.orientation.maxValue > 0) {
3810 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3811 } else if (mRawPointerAxes.orientation.minValue < 0) {
3812 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3813 } else {
3814 mOrientationScale = 0;
3815 }
3816 }
3817 }
3818
3819 mOrientedRanges.haveOrientation = true;
3820
3821 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3822 mOrientedRanges.orientation.source = mSource;
3823 mOrientedRanges.orientation.min = -M_PI_2;
3824 mOrientedRanges.orientation.max = M_PI_2;
3825 mOrientedRanges.orientation.flat = 0;
3826 mOrientedRanges.orientation.fuzz = 0;
3827 mOrientedRanges.orientation.resolution = 0;
3828 }
3829
3830 // Distance
3831 mDistanceScale = 0;
3832 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3833 if (mCalibration.distanceCalibration
3834 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3835 if (mCalibration.haveDistanceScale) {
3836 mDistanceScale = mCalibration.distanceScale;
3837 } else {
3838 mDistanceScale = 1.0f;
3839 }
3840 }
3841
3842 mOrientedRanges.haveDistance = true;
3843
3844 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3845 mOrientedRanges.distance.source = mSource;
3846 mOrientedRanges.distance.min =
3847 mRawPointerAxes.distance.minValue * mDistanceScale;
3848 mOrientedRanges.distance.max =
3849 mRawPointerAxes.distance.maxValue * mDistanceScale;
3850 mOrientedRanges.distance.flat = 0;
3851 mOrientedRanges.distance.fuzz =
3852 mRawPointerAxes.distance.fuzz * mDistanceScale;
3853 mOrientedRanges.distance.resolution = 0;
3854 }
3855
3856 // Compute oriented precision, scales and ranges.
3857 // Note that the maximum value reported is an inclusive maximum value so it is one
3858 // unit less than the total width or height of surface.
3859 switch (mSurfaceOrientation) {
3860 case DISPLAY_ORIENTATION_90:
3861 case DISPLAY_ORIENTATION_270:
3862 mOrientedXPrecision = mYPrecision;
3863 mOrientedYPrecision = mXPrecision;
3864
3865 mOrientedRanges.x.min = mYTranslate;
3866 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3867 mOrientedRanges.x.flat = 0;
3868 mOrientedRanges.x.fuzz = 0;
3869 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3870
3871 mOrientedRanges.y.min = mXTranslate;
3872 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3873 mOrientedRanges.y.flat = 0;
3874 mOrientedRanges.y.fuzz = 0;
3875 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3876 break;
3877
3878 default:
3879 mOrientedXPrecision = mXPrecision;
3880 mOrientedYPrecision = mYPrecision;
3881
3882 mOrientedRanges.x.min = mXTranslate;
3883 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3884 mOrientedRanges.x.flat = 0;
3885 mOrientedRanges.x.fuzz = 0;
3886 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3887
3888 mOrientedRanges.y.min = mYTranslate;
3889 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3890 mOrientedRanges.y.flat = 0;
3891 mOrientedRanges.y.fuzz = 0;
3892 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3893 break;
3894 }
3895
Jason Gerecke71b16e82014-03-10 09:47:59 -07003896 // Location
3897 updateAffineTransformation();
3898
Michael Wrightd02c5b62014-02-10 15:10:22 -08003899 if (mDeviceMode == DEVICE_MODE_POINTER) {
3900 // Compute pointer gesture detection parameters.
3901 float rawDiagonal = hypotf(rawWidth, rawHeight);
3902 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3903
3904 // Scale movements such that one whole swipe of the touch pad covers a
3905 // given area relative to the diagonal size of the display when no acceleration
3906 // is applied.
3907 // Assume that the touch pad has a square aspect ratio such that movements in
3908 // X and Y of the same number of raw units cover the same physical distance.
3909 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3910 * displayDiagonal / rawDiagonal;
3911 mPointerYMovementScale = mPointerXMovementScale;
3912
3913 // Scale zooms to cover a smaller range of the display than movements do.
3914 // This value determines the area around the pointer that is affected by freeform
3915 // pointer gestures.
3916 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3917 * displayDiagonal / rawDiagonal;
3918 mPointerYZoomScale = mPointerXZoomScale;
3919
3920 // Max width between pointers to detect a swipe gesture is more than some fraction
3921 // of the diagonal axis of the touch pad. Touches that are wider than this are
3922 // translated into freeform gestures.
3923 mPointerGestureMaxSwipeWidth =
3924 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3925
3926 // Abort current pointer usages because the state has changed.
3927 abortPointerUsage(when, 0 /*policyFlags*/);
3928 }
3929
3930 // Inform the dispatcher about the changes.
3931 *outResetNeeded = true;
3932 bumpGeneration();
3933 }
3934}
3935
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003936void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003937 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003938 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3939 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3940 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3941 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003942 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3943 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3944 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3945 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003946 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947}
3948
3949void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003950 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3952
3953 mVirtualKeys.clear();
3954
3955 if (virtualKeyDefinitions.size() == 0) {
3956 return;
3957 }
3958
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3960 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003961 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3962 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003964 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3965 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966
3967 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3968 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003969 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003971 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3972 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3974 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003975 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003976 }
3977
3978 virtualKey.keyCode = keyCode;
3979 virtualKey.flags = flags;
3980
3981 // convert the key definition's display coordinates into touch coordinates for a hit box
3982 int32_t halfWidth = virtualKeyDefinition.width / 2;
3983 int32_t halfHeight = virtualKeyDefinition.height / 2;
3984
3985 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3986 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3987 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3988 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3989 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3990 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3991 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3992 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003993 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003994 }
3995}
3996
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003997void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003998 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003999 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004000
4001 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004002 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004003 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4005 i, virtualKey.scanCode, virtualKey.keyCode,
4006 virtualKey.hitLeft, virtualKey.hitRight,
4007 virtualKey.hitTop, virtualKey.hitBottom);
4008 }
4009 }
4010}
4011
4012void TouchInputMapper::parseCalibration() {
4013 const PropertyMap& in = getDevice()->getConfiguration();
4014 Calibration& out = mCalibration;
4015
4016 // Size
4017 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4018 String8 sizeCalibrationString;
4019 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4020 if (sizeCalibrationString == "none") {
4021 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4022 } else if (sizeCalibrationString == "geometric") {
4023 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4024 } else if (sizeCalibrationString == "diameter") {
4025 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4026 } else if (sizeCalibrationString == "box") {
4027 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4028 } else if (sizeCalibrationString == "area") {
4029 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4030 } else if (sizeCalibrationString != "default") {
4031 ALOGW("Invalid value for touch.size.calibration: '%s'",
4032 sizeCalibrationString.string());
4033 }
4034 }
4035
4036 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4037 out.sizeScale);
4038 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4039 out.sizeBias);
4040 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4041 out.sizeIsSummed);
4042
4043 // Pressure
4044 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4045 String8 pressureCalibrationString;
4046 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4047 if (pressureCalibrationString == "none") {
4048 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4049 } else if (pressureCalibrationString == "physical") {
4050 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4051 } else if (pressureCalibrationString == "amplitude") {
4052 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4053 } else if (pressureCalibrationString != "default") {
4054 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4055 pressureCalibrationString.string());
4056 }
4057 }
4058
4059 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4060 out.pressureScale);
4061
4062 // Orientation
4063 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4064 String8 orientationCalibrationString;
4065 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4066 if (orientationCalibrationString == "none") {
4067 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4068 } else if (orientationCalibrationString == "interpolated") {
4069 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4070 } else if (orientationCalibrationString == "vector") {
4071 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4072 } else if (orientationCalibrationString != "default") {
4073 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4074 orientationCalibrationString.string());
4075 }
4076 }
4077
4078 // Distance
4079 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4080 String8 distanceCalibrationString;
4081 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4082 if (distanceCalibrationString == "none") {
4083 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4084 } else if (distanceCalibrationString == "scaled") {
4085 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4086 } else if (distanceCalibrationString != "default") {
4087 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4088 distanceCalibrationString.string());
4089 }
4090 }
4091
4092 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4093 out.distanceScale);
4094
4095 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4096 String8 coverageCalibrationString;
4097 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4098 if (coverageCalibrationString == "none") {
4099 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4100 } else if (coverageCalibrationString == "box") {
4101 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4102 } else if (coverageCalibrationString != "default") {
4103 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4104 coverageCalibrationString.string());
4105 }
4106 }
4107}
4108
4109void TouchInputMapper::resolveCalibration() {
4110 // Size
4111 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4112 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4113 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4114 }
4115 } else {
4116 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4117 }
4118
4119 // Pressure
4120 if (mRawPointerAxes.pressure.valid) {
4121 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4122 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4123 }
4124 } else {
4125 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4126 }
4127
4128 // Orientation
4129 if (mRawPointerAxes.orientation.valid) {
4130 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4131 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4132 }
4133 } else {
4134 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4135 }
4136
4137 // Distance
4138 if (mRawPointerAxes.distance.valid) {
4139 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4140 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4141 }
4142 } else {
4143 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4144 }
4145
4146 // Coverage
4147 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4148 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4149 }
4150}
4151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152void TouchInputMapper::dumpCalibration(std::string& dump) {
4153 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004154
4155 // Size
4156 switch (mCalibration.sizeCalibration) {
4157 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004158 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004159 break;
4160 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004161 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004162 break;
4163 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 break;
4166 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 break;
4169 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 break;
4172 default:
4173 ALOG_ASSERT(false);
4174 }
4175
4176 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 mCalibration.sizeScale);
4179 }
4180
4181 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 mCalibration.sizeBias);
4184 }
4185
4186 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004187 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 toString(mCalibration.sizeIsSummed));
4189 }
4190
4191 // Pressure
4192 switch (mCalibration.pressureCalibration) {
4193 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 break;
4199 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 break;
4202 default:
4203 ALOG_ASSERT(false);
4204 }
4205
4206 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 mCalibration.pressureScale);
4209 }
4210
4211 // Orientation
4212 switch (mCalibration.orientationCalibration) {
4213 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 break;
4216 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004217 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004218 break;
4219 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 break;
4222 default:
4223 ALOG_ASSERT(false);
4224 }
4225
4226 // Distance
4227 switch (mCalibration.distanceCalibration) {
4228 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004229 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004230 break;
4231 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 break;
4234 default:
4235 ALOG_ASSERT(false);
4236 }
4237
4238 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004239 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 mCalibration.distanceScale);
4241 }
4242
4243 switch (mCalibration.coverageCalibration) {
4244 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004245 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004246 break;
4247 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004248 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 break;
4250 default:
4251 ALOG_ASSERT(false);
4252 }
4253}
4254
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4256 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004257
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004258 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4259 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4260 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4261 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4262 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4263 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004264}
4265
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004266void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004267 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4268 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004269}
4270
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271void TouchInputMapper::reset(nsecs_t when) {
4272 mCursorButtonAccumulator.reset(getDevice());
4273 mCursorScrollAccumulator.reset(getDevice());
4274 mTouchButtonAccumulator.reset(getDevice());
4275
4276 mPointerVelocityControl.reset();
4277 mWheelXVelocityControl.reset();
4278 mWheelYVelocityControl.reset();
4279
Michael Wright842500e2015-03-13 17:32:02 -07004280 mRawStatesPending.clear();
4281 mCurrentRawState.clear();
4282 mCurrentCookedState.clear();
4283 mLastRawState.clear();
4284 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004285 mPointerUsage = POINTER_USAGE_NONE;
4286 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004287 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004288 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 mDownTime = 0;
4290
4291 mCurrentVirtualKey.down = false;
4292
4293 mPointerGesture.reset();
4294 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004295 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296
Yi Kong9b14ac62018-07-17 13:48:38 -07004297 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004298 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4299 mPointerController->clearSpots();
4300 }
4301
4302 InputMapper::reset(when);
4303}
4304
Michael Wright842500e2015-03-13 17:32:02 -07004305void TouchInputMapper::resetExternalStylus() {
4306 mExternalStylusState.clear();
4307 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004308 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004309 mExternalStylusDataPending = false;
4310}
4311
Michael Wright43fd19f2015-04-21 19:02:58 +01004312void TouchInputMapper::clearStylusDataPendingFlags() {
4313 mExternalStylusDataPending = false;
4314 mExternalStylusFusionTimeout = LLONG_MAX;
4315}
4316
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317void TouchInputMapper::process(const RawEvent* rawEvent) {
4318 mCursorButtonAccumulator.process(rawEvent);
4319 mCursorScrollAccumulator.process(rawEvent);
4320 mTouchButtonAccumulator.process(rawEvent);
4321
4322 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4323 sync(rawEvent->when);
4324 }
4325}
4326
4327void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004328 const RawState* last = mRawStatesPending.empty() ?
4329 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004330
4331 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004332 mRawStatesPending.emplace_back();
4333
4334 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004335 next->clear();
4336 next->when = when;
4337
Michael Wrightd02c5b62014-02-10 15:10:22 -08004338 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004339 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340 | mCursorButtonAccumulator.getButtonState();
4341
Michael Wright842500e2015-03-13 17:32:02 -07004342 // Sync scroll
4343 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4344 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004345 mCursorScrollAccumulator.finishSync();
4346
Michael Wright842500e2015-03-13 17:32:02 -07004347 // Sync touch
4348 syncTouch(when, next);
4349
4350 // Assign pointer ids.
4351 if (!mHavePointerIds) {
4352 assignPointerIds(last, next);
4353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004354
4355#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004356 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4357 "hovering ids 0x%08x -> 0x%08x",
4358 last->rawPointerData.pointerCount,
4359 next->rawPointerData.pointerCount,
4360 last->rawPointerData.touchingIdBits.value,
4361 next->rawPointerData.touchingIdBits.value,
4362 last->rawPointerData.hoveringIdBits.value,
4363 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364#endif
4365
Michael Wright842500e2015-03-13 17:32:02 -07004366 processRawTouches(false /*timeout*/);
4367}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004368
Michael Wright842500e2015-03-13 17:32:02 -07004369void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4371 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004372 mCurrentRawState.clear();
4373 mRawStatesPending.clear();
4374 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375 }
4376
Michael Wright842500e2015-03-13 17:32:02 -07004377 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4378 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4379 // touching the current state will only observe the events that have been dispatched to the
4380 // rest of the pipeline.
4381 const size_t N = mRawStatesPending.size();
4382 size_t count;
4383 for(count = 0; count < N; count++) {
4384 const RawState& next = mRawStatesPending[count];
4385
4386 // A failure to assign the stylus id means that we're waiting on stylus data
4387 // and so should defer the rest of the pipeline.
4388 if (assignExternalStylusId(next, timeout)) {
4389 break;
4390 }
4391
4392 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004393 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004394 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004395 if (mCurrentRawState.when < mLastRawState.when) {
4396 mCurrentRawState.when = mLastRawState.when;
4397 }
Michael Wright842500e2015-03-13 17:32:02 -07004398 cookAndDispatch(mCurrentRawState.when);
4399 }
4400 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004401 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004402 }
4403
Michael Wright842500e2015-03-13 17:32:02 -07004404 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004405 if (timeout) {
4406 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4407 clearStylusDataPendingFlags();
4408 mCurrentRawState.copyFrom(mLastRawState);
4409#if DEBUG_STYLUS_FUSION
4410 ALOGD("Timeout expired, synthesizing event with new stylus data");
4411#endif
4412 cookAndDispatch(when);
4413 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4414 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4415 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4416 }
Michael Wright842500e2015-03-13 17:32:02 -07004417 }
4418}
4419
4420void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4421 // Always start with a clean state.
4422 mCurrentCookedState.clear();
4423
4424 // Apply stylus buttons to current raw state.
4425 applyExternalStylusButtonState(when);
4426
4427 // Handle policy on initial down or hover events.
4428 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4429 && mCurrentRawState.rawPointerData.pointerCount != 0;
4430
4431 uint32_t policyFlags = 0;
4432 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4433 if (initialDown || buttonsPressed) {
4434 // If this is a touch screen, hide the pointer on an initial down.
4435 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4436 getContext()->fadePointer();
4437 }
4438
4439 if (mParameters.wake) {
4440 policyFlags |= POLICY_FLAG_WAKE;
4441 }
4442 }
4443
4444 // Consume raw off-screen touches before cooking pointer data.
4445 // If touches are consumed, subsequent code will not receive any pointer data.
4446 if (consumeRawTouches(when, policyFlags)) {
4447 mCurrentRawState.rawPointerData.clear();
4448 }
4449
4450 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4451 // with cooked pointer data that has the same ids and indices as the raw data.
4452 // The following code can use either the raw or cooked data, as needed.
4453 cookPointerData();
4454
4455 // Apply stylus pressure to current cooked state.
4456 applyExternalStylusTouchState(when);
4457
4458 // Synthesize key down from raw buttons if needed.
4459 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004460 mViewport.displayId, policyFlags,
4461 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004462
4463 // Dispatch the touches either directly or by translation through a pointer on screen.
4464 if (mDeviceMode == DEVICE_MODE_POINTER) {
4465 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4466 !idBits.isEmpty(); ) {
4467 uint32_t id = idBits.clearFirstMarkedBit();
4468 const RawPointerData::Pointer& pointer =
4469 mCurrentRawState.rawPointerData.pointerForId(id);
4470 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4471 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4472 mCurrentCookedState.stylusIdBits.markBit(id);
4473 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4474 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4475 mCurrentCookedState.fingerIdBits.markBit(id);
4476 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4477 mCurrentCookedState.mouseIdBits.markBit(id);
4478 }
4479 }
4480 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4481 !idBits.isEmpty(); ) {
4482 uint32_t id = idBits.clearFirstMarkedBit();
4483 const RawPointerData::Pointer& pointer =
4484 mCurrentRawState.rawPointerData.pointerForId(id);
4485 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4486 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4487 mCurrentCookedState.stylusIdBits.markBit(id);
4488 }
4489 }
4490
4491 // Stylus takes precedence over all tools, then mouse, then finger.
4492 PointerUsage pointerUsage = mPointerUsage;
4493 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4494 mCurrentCookedState.mouseIdBits.clear();
4495 mCurrentCookedState.fingerIdBits.clear();
4496 pointerUsage = POINTER_USAGE_STYLUS;
4497 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4498 mCurrentCookedState.fingerIdBits.clear();
4499 pointerUsage = POINTER_USAGE_MOUSE;
4500 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4501 isPointerDown(mCurrentRawState.buttonState)) {
4502 pointerUsage = POINTER_USAGE_GESTURES;
4503 }
4504
4505 dispatchPointerUsage(when, policyFlags, pointerUsage);
4506 } else {
4507 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004508 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004509 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4510 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4511
4512 mPointerController->setButtonState(mCurrentRawState.buttonState);
4513 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4514 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004515 mCurrentCookedState.cookedPointerData.touchingIdBits,
4516 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004517 }
4518
Michael Wright8e812822015-06-22 16:18:21 +01004519 if (!mCurrentMotionAborted) {
4520 dispatchButtonRelease(when, policyFlags);
4521 dispatchHoverExit(when, policyFlags);
4522 dispatchTouches(when, policyFlags);
4523 dispatchHoverEnterAndMove(when, policyFlags);
4524 dispatchButtonPress(when, policyFlags);
4525 }
4526
4527 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4528 mCurrentMotionAborted = false;
4529 }
Michael Wright842500e2015-03-13 17:32:02 -07004530 }
4531
4532 // Synthesize key up from raw buttons if needed.
4533 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004534 mViewport.displayId, policyFlags,
4535 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004536
4537 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004538 mCurrentRawState.rawVScroll = 0;
4539 mCurrentRawState.rawHScroll = 0;
4540
4541 // Copy current touch to last touch in preparation for the next cycle.
4542 mLastRawState.copyFrom(mCurrentRawState);
4543 mLastCookedState.copyFrom(mCurrentCookedState);
4544}
4545
4546void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004547 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004548 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4549 }
4550}
4551
4552void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004553 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4554 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004555
Michael Wright53dca3a2015-04-23 17:39:53 +01004556 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4557 float pressure = mExternalStylusState.pressure;
4558 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4559 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4560 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4561 }
4562 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4563 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4564
4565 PointerProperties& properties =
4566 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004567 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4568 properties.toolType = mExternalStylusState.toolType;
4569 }
4570 }
4571}
4572
4573bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4574 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4575 return false;
4576 }
4577
4578 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4579 && state.rawPointerData.pointerCount != 0;
4580 if (initialDown) {
4581 if (mExternalStylusState.pressure != 0.0f) {
4582#if DEBUG_STYLUS_FUSION
4583 ALOGD("Have both stylus and touch data, beginning fusion");
4584#endif
4585 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4586 } else if (timeout) {
4587#if DEBUG_STYLUS_FUSION
4588 ALOGD("Timeout expired, assuming touch is not a stylus.");
4589#endif
4590 resetExternalStylus();
4591 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004592 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4593 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004594 }
4595#if DEBUG_STYLUS_FUSION
4596 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004597 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004598#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004599 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004600 return true;
4601 }
4602 }
4603
4604 // Check if the stylus pointer has gone up.
4605 if (mExternalStylusId != -1 &&
4606 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4607#if DEBUG_STYLUS_FUSION
4608 ALOGD("Stylus pointer is going up");
4609#endif
4610 mExternalStylusId = -1;
4611 }
4612
4613 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004614}
4615
4616void TouchInputMapper::timeoutExpired(nsecs_t when) {
4617 if (mDeviceMode == DEVICE_MODE_POINTER) {
4618 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4619 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4620 }
Michael Wright842500e2015-03-13 17:32:02 -07004621 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004622 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004623 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004624 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4625 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004626 }
4627 }
4628}
4629
4630void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004631 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004632 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004633 // We're either in the middle of a fused stream of data or we're waiting on data before
4634 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4635 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004636 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004637 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 }
4639}
4640
4641bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4642 // Check for release of a virtual key.
4643 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004644 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 // Pointer went up while virtual key was down.
4646 mCurrentVirtualKey.down = false;
4647 if (!mCurrentVirtualKey.ignored) {
4648#if DEBUG_VIRTUAL_KEYS
4649 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4650 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4651#endif
4652 dispatchVirtualKey(when, policyFlags,
4653 AKEY_EVENT_ACTION_UP,
4654 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4655 }
4656 return true;
4657 }
4658
Michael Wright842500e2015-03-13 17:32:02 -07004659 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4660 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4661 const RawPointerData::Pointer& pointer =
4662 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4664 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4665 // Pointer is still within the space of the virtual key.
4666 return true;
4667 }
4668 }
4669
4670 // Pointer left virtual key area or another pointer also went down.
4671 // Send key cancellation but do not consume the touch yet.
4672 // This is useful when the user swipes through from the virtual key area
4673 // into the main display surface.
4674 mCurrentVirtualKey.down = false;
4675 if (!mCurrentVirtualKey.ignored) {
4676#if DEBUG_VIRTUAL_KEYS
4677 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4678 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4679#endif
4680 dispatchVirtualKey(when, policyFlags,
4681 AKEY_EVENT_ACTION_UP,
4682 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4683 | AKEY_EVENT_FLAG_CANCELED);
4684 }
4685 }
4686
Michael Wright842500e2015-03-13 17:32:02 -07004687 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4688 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004689 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004690 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4691 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004692 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4693 // If exactly one pointer went down, check for virtual key hit.
4694 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004695 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4697 if (virtualKey) {
4698 mCurrentVirtualKey.down = true;
4699 mCurrentVirtualKey.downTime = when;
4700 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4701 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4702 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4703 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4704
4705 if (!mCurrentVirtualKey.ignored) {
4706#if DEBUG_VIRTUAL_KEYS
4707 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4708 mCurrentVirtualKey.keyCode,
4709 mCurrentVirtualKey.scanCode);
4710#endif
4711 dispatchVirtualKey(when, policyFlags,
4712 AKEY_EVENT_ACTION_DOWN,
4713 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4714 }
4715 }
4716 }
4717 return true;
4718 }
4719 }
4720
4721 // Disable all virtual key touches that happen within a short time interval of the
4722 // most recent touch within the screen area. The idea is to filter out stray
4723 // virtual key presses when interacting with the touch screen.
4724 //
4725 // Problems we're trying to solve:
4726 //
4727 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4728 // virtual key area that is implemented by a separate touch panel and accidentally
4729 // triggers a virtual key.
4730 //
4731 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4732 // area and accidentally triggers a virtual key. This often happens when virtual keys
4733 // are layed out below the screen near to where the on screen keyboard's space bar
4734 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004735 if (mConfig.virtualKeyQuietTime > 0 &&
4736 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004737 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4738 }
4739 return false;
4740}
4741
4742void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4743 int32_t keyEventAction, int32_t keyEventFlags) {
4744 int32_t keyCode = mCurrentVirtualKey.keyCode;
4745 int32_t scanCode = mCurrentVirtualKey.scanCode;
4746 nsecs_t downTime = mCurrentVirtualKey.downTime;
4747 int32_t metaState = mContext->getGlobalMetaState();
4748 policyFlags |= POLICY_FLAG_VIRTUAL;
4749
Prabir Pradhan42611e02018-11-27 14:04:02 -08004750 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4751 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004752 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 getListener()->notifyKey(&args);
4754}
4755
Michael Wright8e812822015-06-22 16:18:21 +01004756void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4757 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4758 if (!currentIdBits.isEmpty()) {
4759 int32_t metaState = getContext()->getGlobalMetaState();
4760 int32_t buttonState = mCurrentCookedState.buttonState;
4761 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4762 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4763 mCurrentCookedState.cookedPointerData.pointerProperties,
4764 mCurrentCookedState.cookedPointerData.pointerCoords,
4765 mCurrentCookedState.cookedPointerData.idToIndex,
4766 currentIdBits, -1,
4767 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4768 mCurrentMotionAborted = true;
4769 }
4770}
4771
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004773 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4774 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004776 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004777
4778 if (currentIdBits == lastIdBits) {
4779 if (!currentIdBits.isEmpty()) {
4780 // No pointer id changes so this is a move event.
4781 // The listener takes care of batching moves so we don't have to deal with that here.
4782 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004783 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004785 mCurrentCookedState.cookedPointerData.pointerProperties,
4786 mCurrentCookedState.cookedPointerData.pointerCoords,
4787 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 currentIdBits, -1,
4789 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4790 }
4791 } else {
4792 // There may be pointers going up and pointers going down and pointers moving
4793 // all at the same time.
4794 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4795 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4796 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4797 BitSet32 dispatchedIdBits(lastIdBits.value);
4798
4799 // Update last coordinates of pointers that have moved so that we observe the new
4800 // pointer positions at the same time as other pointers that have just gone up.
4801 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004802 mCurrentCookedState.cookedPointerData.pointerProperties,
4803 mCurrentCookedState.cookedPointerData.pointerCoords,
4804 mCurrentCookedState.cookedPointerData.idToIndex,
4805 mLastCookedState.cookedPointerData.pointerProperties,
4806 mLastCookedState.cookedPointerData.pointerCoords,
4807 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004808 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004809 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810 moveNeeded = true;
4811 }
4812
4813 // Dispatch pointer up events.
4814 while (!upIdBits.isEmpty()) {
4815 uint32_t upId = upIdBits.clearFirstMarkedBit();
4816
4817 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004818 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004819 mLastCookedState.cookedPointerData.pointerProperties,
4820 mLastCookedState.cookedPointerData.pointerCoords,
4821 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004822 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 dispatchedIdBits.clearBit(upId);
4824 }
4825
4826 // Dispatch move events if any of the remaining pointers moved from their old locations.
4827 // Although applications receive new locations as part of individual pointer up
4828 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004829 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4831 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004832 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004833 mCurrentCookedState.cookedPointerData.pointerProperties,
4834 mCurrentCookedState.cookedPointerData.pointerCoords,
4835 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004836 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004837 }
4838
4839 // Dispatch pointer down events using the new pointer locations.
4840 while (!downIdBits.isEmpty()) {
4841 uint32_t downId = downIdBits.clearFirstMarkedBit();
4842 dispatchedIdBits.markBit(downId);
4843
4844 if (dispatchedIdBits.count() == 1) {
4845 // First pointer is going down. Set down time.
4846 mDownTime = when;
4847 }
4848
4849 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004850 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004851 mCurrentCookedState.cookedPointerData.pointerProperties,
4852 mCurrentCookedState.cookedPointerData.pointerCoords,
4853 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004854 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 }
4856 }
4857}
4858
4859void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4860 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004861 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4862 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 int32_t metaState = getContext()->getGlobalMetaState();
4864 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004865 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004866 mLastCookedState.cookedPointerData.pointerProperties,
4867 mLastCookedState.cookedPointerData.pointerCoords,
4868 mLastCookedState.cookedPointerData.idToIndex,
4869 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4871 mSentHoverEnter = false;
4872 }
4873}
4874
4875void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004876 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4877 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 int32_t metaState = getContext()->getGlobalMetaState();
4879 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004880 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004881 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004882 mCurrentCookedState.cookedPointerData.pointerProperties,
4883 mCurrentCookedState.cookedPointerData.pointerCoords,
4884 mCurrentCookedState.cookedPointerData.idToIndex,
4885 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004886 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4887 mSentHoverEnter = true;
4888 }
4889
4890 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004891 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004892 mCurrentRawState.buttonState, 0,
4893 mCurrentCookedState.cookedPointerData.pointerProperties,
4894 mCurrentCookedState.cookedPointerData.pointerCoords,
4895 mCurrentCookedState.cookedPointerData.idToIndex,
4896 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4898 }
4899}
4900
Michael Wright7b159c92015-05-14 14:48:03 +01004901void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4902 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4903 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4904 const int32_t metaState = getContext()->getGlobalMetaState();
4905 int32_t buttonState = mLastCookedState.buttonState;
4906 while (!releasedButtons.isEmpty()) {
4907 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4908 buttonState &= ~actionButton;
4909 dispatchMotion(when, policyFlags, mSource,
4910 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4911 0, metaState, buttonState, 0,
4912 mCurrentCookedState.cookedPointerData.pointerProperties,
4913 mCurrentCookedState.cookedPointerData.pointerCoords,
4914 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4915 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4916 }
4917}
4918
4919void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4920 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4921 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4922 const int32_t metaState = getContext()->getGlobalMetaState();
4923 int32_t buttonState = mLastCookedState.buttonState;
4924 while (!pressedButtons.isEmpty()) {
4925 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4926 buttonState |= actionButton;
4927 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4928 0, metaState, buttonState, 0,
4929 mCurrentCookedState.cookedPointerData.pointerProperties,
4930 mCurrentCookedState.cookedPointerData.pointerCoords,
4931 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4932 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4933 }
4934}
4935
4936const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4937 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4938 return cookedPointerData.touchingIdBits;
4939 }
4940 return cookedPointerData.hoveringIdBits;
4941}
4942
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004944 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004945
Michael Wright842500e2015-03-13 17:32:02 -07004946 mCurrentCookedState.cookedPointerData.clear();
4947 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4948 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4949 mCurrentRawState.rawPointerData.hoveringIdBits;
4950 mCurrentCookedState.cookedPointerData.touchingIdBits =
4951 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004952
Michael Wright7b159c92015-05-14 14:48:03 +01004953 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4954 mCurrentCookedState.buttonState = 0;
4955 } else {
4956 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4957 }
4958
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959 // Walk through the the active pointers and map device coordinates onto
4960 // surface coordinates and adjust for display orientation.
4961 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004962 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963
4964 // Size
4965 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4966 switch (mCalibration.sizeCalibration) {
4967 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4968 case Calibration::SIZE_CALIBRATION_DIAMETER:
4969 case Calibration::SIZE_CALIBRATION_BOX:
4970 case Calibration::SIZE_CALIBRATION_AREA:
4971 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4972 touchMajor = in.touchMajor;
4973 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4974 toolMajor = in.toolMajor;
4975 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4976 size = mRawPointerAxes.touchMinor.valid
4977 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4978 } else if (mRawPointerAxes.touchMajor.valid) {
4979 toolMajor = touchMajor = in.touchMajor;
4980 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4981 ? in.touchMinor : in.touchMajor;
4982 size = mRawPointerAxes.touchMinor.valid
4983 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4984 } else if (mRawPointerAxes.toolMajor.valid) {
4985 touchMajor = toolMajor = in.toolMajor;
4986 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4987 ? in.toolMinor : in.toolMajor;
4988 size = mRawPointerAxes.toolMinor.valid
4989 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4990 } else {
4991 ALOG_ASSERT(false, "No touch or tool axes. "
4992 "Size calibration should have been resolved to NONE.");
4993 touchMajor = 0;
4994 touchMinor = 0;
4995 toolMajor = 0;
4996 toolMinor = 0;
4997 size = 0;
4998 }
4999
5000 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005001 uint32_t touchingCount =
5002 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005003 if (touchingCount > 1) {
5004 touchMajor /= touchingCount;
5005 touchMinor /= touchingCount;
5006 toolMajor /= touchingCount;
5007 toolMinor /= touchingCount;
5008 size /= touchingCount;
5009 }
5010 }
5011
5012 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5013 touchMajor *= mGeometricScale;
5014 touchMinor *= mGeometricScale;
5015 toolMajor *= mGeometricScale;
5016 toolMinor *= mGeometricScale;
5017 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5018 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5019 touchMinor = touchMajor;
5020 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5021 toolMinor = toolMajor;
5022 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5023 touchMinor = touchMajor;
5024 toolMinor = toolMajor;
5025 }
5026
5027 mCalibration.applySizeScaleAndBias(&touchMajor);
5028 mCalibration.applySizeScaleAndBias(&touchMinor);
5029 mCalibration.applySizeScaleAndBias(&toolMajor);
5030 mCalibration.applySizeScaleAndBias(&toolMinor);
5031 size *= mSizeScale;
5032 break;
5033 default:
5034 touchMajor = 0;
5035 touchMinor = 0;
5036 toolMajor = 0;
5037 toolMinor = 0;
5038 size = 0;
5039 break;
5040 }
5041
5042 // Pressure
5043 float pressure;
5044 switch (mCalibration.pressureCalibration) {
5045 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5046 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5047 pressure = in.pressure * mPressureScale;
5048 break;
5049 default:
5050 pressure = in.isHovering ? 0 : 1;
5051 break;
5052 }
5053
5054 // Tilt and Orientation
5055 float tilt;
5056 float orientation;
5057 if (mHaveTilt) {
5058 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5059 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5060 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5061 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5062 } else {
5063 tilt = 0;
5064
5065 switch (mCalibration.orientationCalibration) {
5066 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5067 orientation = in.orientation * mOrientationScale;
5068 break;
5069 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5070 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5071 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5072 if (c1 != 0 || c2 != 0) {
5073 orientation = atan2f(c1, c2) * 0.5f;
5074 float confidence = hypotf(c1, c2);
5075 float scale = 1.0f + confidence / 16.0f;
5076 touchMajor *= scale;
5077 touchMinor /= scale;
5078 toolMajor *= scale;
5079 toolMinor /= scale;
5080 } else {
5081 orientation = 0;
5082 }
5083 break;
5084 }
5085 default:
5086 orientation = 0;
5087 }
5088 }
5089
5090 // Distance
5091 float distance;
5092 switch (mCalibration.distanceCalibration) {
5093 case Calibration::DISTANCE_CALIBRATION_SCALED:
5094 distance = in.distance * mDistanceScale;
5095 break;
5096 default:
5097 distance = 0;
5098 }
5099
5100 // Coverage
5101 int32_t rawLeft, rawTop, rawRight, rawBottom;
5102 switch (mCalibration.coverageCalibration) {
5103 case Calibration::COVERAGE_CALIBRATION_BOX:
5104 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5105 rawRight = in.toolMinor & 0x0000ffff;
5106 rawBottom = in.toolMajor & 0x0000ffff;
5107 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5108 break;
5109 default:
5110 rawLeft = rawTop = rawRight = rawBottom = 0;
5111 break;
5112 }
5113
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005114 // Adjust X,Y coords for device calibration
5115 // TODO: Adjust coverage coords?
5116 float xTransformed = in.x, yTransformed = in.y;
5117 mAffineTransform.applyTo(xTransformed, yTransformed);
5118
5119 // Adjust X, Y, and coverage coords for surface orientation.
5120 float x, y;
5121 float left, top, right, bottom;
5122
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 switch (mSurfaceOrientation) {
5124 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005125 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5126 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5128 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5129 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5130 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5131 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005132 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5134 }
5135 break;
5136 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005137 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005138 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005139 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5140 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5142 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5143 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005144 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5146 }
5147 break;
5148 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005149 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005150 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005151 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5152 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5154 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5155 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005156 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5158 }
5159 break;
5160 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005161 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5162 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5164 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5165 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5166 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5167 break;
5168 }
5169
5170 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005171 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 out.clear();
5173 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5174 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5175 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5176 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5177 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5178 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5179 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5180 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5181 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5182 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5183 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5184 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5185 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5186 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5187 } else {
5188 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5189 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5190 }
5191
5192 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005193 PointerProperties& properties =
5194 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 uint32_t id = in.id;
5196 properties.clear();
5197 properties.id = id;
5198 properties.toolType = in.toolType;
5199
5200 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005201 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 }
5203}
5204
5205void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5206 PointerUsage pointerUsage) {
5207 if (pointerUsage != mPointerUsage) {
5208 abortPointerUsage(when, policyFlags);
5209 mPointerUsage = pointerUsage;
5210 }
5211
5212 switch (mPointerUsage) {
5213 case POINTER_USAGE_GESTURES:
5214 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5215 break;
5216 case POINTER_USAGE_STYLUS:
5217 dispatchPointerStylus(when, policyFlags);
5218 break;
5219 case POINTER_USAGE_MOUSE:
5220 dispatchPointerMouse(when, policyFlags);
5221 break;
5222 default:
5223 break;
5224 }
5225}
5226
5227void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5228 switch (mPointerUsage) {
5229 case POINTER_USAGE_GESTURES:
5230 abortPointerGestures(when, policyFlags);
5231 break;
5232 case POINTER_USAGE_STYLUS:
5233 abortPointerStylus(when, policyFlags);
5234 break;
5235 case POINTER_USAGE_MOUSE:
5236 abortPointerMouse(when, policyFlags);
5237 break;
5238 default:
5239 break;
5240 }
5241
5242 mPointerUsage = POINTER_USAGE_NONE;
5243}
5244
5245void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5246 bool isTimeout) {
5247 // Update current gesture coordinates.
5248 bool cancelPreviousGesture, finishPreviousGesture;
5249 bool sendEvents = preparePointerGestures(when,
5250 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5251 if (!sendEvents) {
5252 return;
5253 }
5254 if (finishPreviousGesture) {
5255 cancelPreviousGesture = false;
5256 }
5257
5258 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005259 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5260 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005261 if (finishPreviousGesture || cancelPreviousGesture) {
5262 mPointerController->clearSpots();
5263 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005264
5265 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5266 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5267 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005268 mPointerGesture.currentGestureIdBits,
5269 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005270 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 } else {
5272 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5273 }
5274
5275 // Show or hide the pointer if needed.
5276 switch (mPointerGesture.currentGestureMode) {
5277 case PointerGesture::NEUTRAL:
5278 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005279 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5280 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 // Remind the user of where the pointer is after finishing a gesture with spots.
5282 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5283 }
5284 break;
5285 case PointerGesture::TAP:
5286 case PointerGesture::TAP_DRAG:
5287 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5288 case PointerGesture::HOVER:
5289 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005290 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291 // Unfade the pointer when the current gesture manipulates the
5292 // area directly under the pointer.
5293 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5294 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005295 case PointerGesture::FREEFORM:
5296 // Fade the pointer when the current gesture manipulates a different
5297 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005298 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5300 } else {
5301 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5302 }
5303 break;
5304 }
5305
5306 // Send events!
5307 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005308 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309
5310 // Update last coordinates of pointers that have moved so that we observe the new
5311 // pointer positions at the same time as other pointers that have just gone up.
5312 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5313 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5314 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5315 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5316 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5317 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5318 bool moveNeeded = false;
5319 if (down && !cancelPreviousGesture && !finishPreviousGesture
5320 && !mPointerGesture.lastGestureIdBits.isEmpty()
5321 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5322 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5323 & mPointerGesture.lastGestureIdBits.value);
5324 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5325 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5326 mPointerGesture.lastGestureProperties,
5327 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5328 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005329 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005330 moveNeeded = true;
5331 }
5332 }
5333
5334 // Send motion events for all pointers that went up or were canceled.
5335 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5336 if (!dispatchedGestureIdBits.isEmpty()) {
5337 if (cancelPreviousGesture) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005338 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5339 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5340 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5341 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5342 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343
5344 dispatchedGestureIdBits.clear();
5345 } else {
5346 BitSet32 upGestureIdBits;
5347 if (finishPreviousGesture) {
5348 upGestureIdBits = dispatchedGestureIdBits;
5349 } else {
5350 upGestureIdBits.value = dispatchedGestureIdBits.value
5351 & ~mPointerGesture.currentGestureIdBits.value;
5352 }
5353 while (!upGestureIdBits.isEmpty()) {
5354 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5355
5356 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005357 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005358 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5359 mPointerGesture.lastGestureProperties,
5360 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5361 dispatchedGestureIdBits, id,
5362 0, 0, mPointerGesture.downTime);
5363
5364 dispatchedGestureIdBits.clearBit(id);
5365 }
5366 }
5367 }
5368
5369 // Send motion events for all pointers that moved.
5370 if (moveNeeded) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005371 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5372 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5373 mPointerGesture.currentGestureProperties,
5374 mPointerGesture.currentGestureCoords,
5375 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5376 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005377 }
5378
5379 // Send motion events for all pointers that went down.
5380 if (down) {
5381 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5382 & ~dispatchedGestureIdBits.value);
5383 while (!downGestureIdBits.isEmpty()) {
5384 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5385 dispatchedGestureIdBits.markBit(id);
5386
5387 if (dispatchedGestureIdBits.count() == 1) {
5388 mPointerGesture.downTime = when;
5389 }
5390
5391 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005392 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 mPointerGesture.currentGestureProperties,
5394 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5395 dispatchedGestureIdBits, id,
5396 0, 0, mPointerGesture.downTime);
5397 }
5398 }
5399
5400 // Send motion events for hover.
5401 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005402 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5403 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5404 mPointerGesture.currentGestureProperties,
5405 mPointerGesture.currentGestureCoords,
5406 mPointerGesture.currentGestureIdToIndex,
5407 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 } else if (dispatchedGestureIdBits.isEmpty()
5409 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5410 // Synthesize a hover move event after all pointers go up to indicate that
5411 // the pointer is hovering again even if the user is not currently touching
5412 // the touch pad. This ensures that a view will receive a fresh hover enter
5413 // event after a tap.
5414 float x, y;
5415 mPointerController->getPosition(&x, &y);
5416
5417 PointerProperties pointerProperties;
5418 pointerProperties.clear();
5419 pointerProperties.id = 0;
5420 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5421
5422 PointerCoords pointerCoords;
5423 pointerCoords.clear();
5424 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5425 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5426
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005427 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005428 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5429 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5430 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005431 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
5432 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433 getListener()->notifyMotion(&args);
5434 }
5435
5436 // Update state.
5437 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5438 if (!down) {
5439 mPointerGesture.lastGestureIdBits.clear();
5440 } else {
5441 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5442 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5443 uint32_t id = idBits.clearFirstMarkedBit();
5444 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5445 mPointerGesture.lastGestureProperties[index].copyFrom(
5446 mPointerGesture.currentGestureProperties[index]);
5447 mPointerGesture.lastGestureCoords[index].copyFrom(
5448 mPointerGesture.currentGestureCoords[index]);
5449 mPointerGesture.lastGestureIdToIndex[id] = index;
5450 }
5451 }
5452}
5453
5454void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5455 // Cancel previously dispatches pointers.
5456 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5457 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005458 int32_t buttonState = mCurrentRawState.buttonState;
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005459 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5460 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5461 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5462 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5463 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005464 }
5465
5466 // Reset the current pointer gesture.
5467 mPointerGesture.reset();
5468 mPointerVelocityControl.reset();
5469
5470 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005471 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5473 mPointerController->clearSpots();
5474 }
5475}
5476
5477bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5478 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5479 *outCancelPreviousGesture = false;
5480 *outFinishPreviousGesture = false;
5481
5482 // Handle TAP timeout.
5483 if (isTimeout) {
5484#if DEBUG_GESTURES
5485 ALOGD("Gestures: Processing timeout");
5486#endif
5487
5488 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5489 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5490 // The tap/drag timeout has not yet expired.
5491 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5492 + mConfig.pointerGestureTapDragInterval);
5493 } else {
5494 // The tap is finished.
5495#if DEBUG_GESTURES
5496 ALOGD("Gestures: TAP finished");
5497#endif
5498 *outFinishPreviousGesture = true;
5499
5500 mPointerGesture.activeGestureId = -1;
5501 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5502 mPointerGesture.currentGestureIdBits.clear();
5503
5504 mPointerVelocityControl.reset();
5505 return true;
5506 }
5507 }
5508
5509 // We did not handle this timeout.
5510 return false;
5511 }
5512
Michael Wright842500e2015-03-13 17:32:02 -07005513 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5514 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515
5516 // Update the velocity tracker.
5517 {
5518 VelocityTracker::Position positions[MAX_POINTERS];
5519 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005520 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005522 const RawPointerData::Pointer& pointer =
5523 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 positions[count].x = pointer.x * mPointerXMovementScale;
5525 positions[count].y = pointer.y * mPointerYMovementScale;
5526 }
5527 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005528 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 }
5530
5531 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5532 // to NEUTRAL, then we should not generate tap event.
5533 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5534 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5535 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5536 mPointerGesture.resetTap();
5537 }
5538
5539 // Pick a new active touch id if needed.
5540 // Choose an arbitrary pointer that just went down, if there is one.
5541 // Otherwise choose an arbitrary remaining pointer.
5542 // This guarantees we always have an active touch id when there is at least one pointer.
5543 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005544 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5545 int32_t activeTouchId = lastActiveTouchId;
5546 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005547 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005549 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005550 mPointerGesture.firstTouchTime = when;
5551 }
Michael Wright842500e2015-03-13 17:32:02 -07005552 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005553 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005555 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 } else {
5557 activeTouchId = mPointerGesture.activeTouchId = -1;
5558 }
5559 }
5560
5561 // Determine whether we are in quiet time.
5562 bool isQuietTime = false;
5563 if (activeTouchId < 0) {
5564 mPointerGesture.resetQuietTime();
5565 } else {
5566 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5567 if (!isQuietTime) {
5568 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5569 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5570 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5571 && currentFingerCount < 2) {
5572 // Enter quiet time when exiting swipe or freeform state.
5573 // This is to prevent accidentally entering the hover state and flinging the
5574 // pointer when finishing a swipe and there is still one pointer left onscreen.
5575 isQuietTime = true;
5576 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5577 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005578 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005579 // Enter quiet time when releasing the button and there are still two or more
5580 // fingers down. This may indicate that one finger was used to press the button
5581 // but it has not gone up yet.
5582 isQuietTime = true;
5583 }
5584 if (isQuietTime) {
5585 mPointerGesture.quietTime = when;
5586 }
5587 }
5588 }
5589
5590 // Switch states based on button and pointer state.
5591 if (isQuietTime) {
5592 // Case 1: Quiet time. (QUIET)
5593#if DEBUG_GESTURES
5594 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5595 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5596#endif
5597 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5598 *outFinishPreviousGesture = true;
5599 }
5600
5601 mPointerGesture.activeGestureId = -1;
5602 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5603 mPointerGesture.currentGestureIdBits.clear();
5604
5605 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005606 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5608 // The pointer follows the active touch point.
5609 // Emit DOWN, MOVE, UP events at the pointer location.
5610 //
5611 // Only the active touch matters; other fingers are ignored. This policy helps
5612 // to handle the case where the user places a second finger on the touch pad
5613 // to apply the necessary force to depress an integrated button below the surface.
5614 // We don't want the second finger to be delivered to applications.
5615 //
5616 // For this to work well, we need to make sure to track the pointer that is really
5617 // active. If the user first puts one finger down to click then adds another
5618 // finger to drag then the active pointer should switch to the finger that is
5619 // being dragged.
5620#if DEBUG_GESTURES
5621 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5622 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5623#endif
5624 // Reset state when just starting.
5625 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5626 *outFinishPreviousGesture = true;
5627 mPointerGesture.activeGestureId = 0;
5628 }
5629
5630 // Switch pointers if needed.
5631 // Find the fastest pointer and follow it.
5632 if (activeTouchId >= 0 && currentFingerCount > 1) {
5633 int32_t bestId = -1;
5634 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005635 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 uint32_t id = idBits.clearFirstMarkedBit();
5637 float vx, vy;
5638 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5639 float speed = hypotf(vx, vy);
5640 if (speed > bestSpeed) {
5641 bestId = id;
5642 bestSpeed = speed;
5643 }
5644 }
5645 }
5646 if (bestId >= 0 && bestId != activeTouchId) {
5647 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648#if DEBUG_GESTURES
5649 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5650 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5651#endif
5652 }
5653 }
5654
Jun Mukaifa1706a2015-12-03 01:14:46 -08005655 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005656 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005657 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005658 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005659 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005660 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005661 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5662 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663
5664 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5665 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5666
5667 // Move the pointer using a relative motion.
5668 // When using spots, the click will occur at the position of the anchor
5669 // spot and all other spots will move there.
5670 mPointerController->move(deltaX, deltaY);
5671 } else {
5672 mPointerVelocityControl.reset();
5673 }
5674
5675 float x, y;
5676 mPointerController->getPosition(&x, &y);
5677
5678 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5679 mPointerGesture.currentGestureIdBits.clear();
5680 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5681 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5682 mPointerGesture.currentGestureProperties[0].clear();
5683 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5684 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5685 mPointerGesture.currentGestureCoords[0].clear();
5686 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5687 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5688 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5689 } else if (currentFingerCount == 0) {
5690 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5691 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5692 *outFinishPreviousGesture = true;
5693 }
5694
5695 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5696 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5697 bool tapped = false;
5698 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5699 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5700 && lastFingerCount == 1) {
5701 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5702 float x, y;
5703 mPointerController->getPosition(&x, &y);
5704 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5705 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5706#if DEBUG_GESTURES
5707 ALOGD("Gestures: TAP");
5708#endif
5709
5710 mPointerGesture.tapUpTime = when;
5711 getContext()->requestTimeoutAtTime(when
5712 + mConfig.pointerGestureTapDragInterval);
5713
5714 mPointerGesture.activeGestureId = 0;
5715 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5716 mPointerGesture.currentGestureIdBits.clear();
5717 mPointerGesture.currentGestureIdBits.markBit(
5718 mPointerGesture.activeGestureId);
5719 mPointerGesture.currentGestureIdToIndex[
5720 mPointerGesture.activeGestureId] = 0;
5721 mPointerGesture.currentGestureProperties[0].clear();
5722 mPointerGesture.currentGestureProperties[0].id =
5723 mPointerGesture.activeGestureId;
5724 mPointerGesture.currentGestureProperties[0].toolType =
5725 AMOTION_EVENT_TOOL_TYPE_FINGER;
5726 mPointerGesture.currentGestureCoords[0].clear();
5727 mPointerGesture.currentGestureCoords[0].setAxisValue(
5728 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5729 mPointerGesture.currentGestureCoords[0].setAxisValue(
5730 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5731 mPointerGesture.currentGestureCoords[0].setAxisValue(
5732 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5733
5734 tapped = true;
5735 } else {
5736#if DEBUG_GESTURES
5737 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5738 x - mPointerGesture.tapX,
5739 y - mPointerGesture.tapY);
5740#endif
5741 }
5742 } else {
5743#if DEBUG_GESTURES
5744 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5745 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5746 (when - mPointerGesture.tapDownTime) * 0.000001f);
5747 } else {
5748 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5749 }
5750#endif
5751 }
5752 }
5753
5754 mPointerVelocityControl.reset();
5755
5756 if (!tapped) {
5757#if DEBUG_GESTURES
5758 ALOGD("Gestures: NEUTRAL");
5759#endif
5760 mPointerGesture.activeGestureId = -1;
5761 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5762 mPointerGesture.currentGestureIdBits.clear();
5763 }
5764 } else if (currentFingerCount == 1) {
5765 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5766 // The pointer follows the active touch point.
5767 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5768 // When in TAP_DRAG, emit MOVE events at the pointer location.
5769 ALOG_ASSERT(activeTouchId >= 0);
5770
5771 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5772 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5773 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5774 float x, y;
5775 mPointerController->getPosition(&x, &y);
5776 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5777 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5778 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5779 } else {
5780#if DEBUG_GESTURES
5781 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5782 x - mPointerGesture.tapX,
5783 y - mPointerGesture.tapY);
5784#endif
5785 }
5786 } else {
5787#if DEBUG_GESTURES
5788 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5789 (when - mPointerGesture.tapUpTime) * 0.000001f);
5790#endif
5791 }
5792 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5793 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5794 }
5795
Jun Mukaifa1706a2015-12-03 01:14:46 -08005796 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005797 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005798 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005799 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005800 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005801 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005802 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5803 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005804
5805 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5806 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5807
5808 // Move the pointer using a relative motion.
5809 // When using spots, the hover or drag will occur at the position of the anchor spot.
5810 mPointerController->move(deltaX, deltaY);
5811 } else {
5812 mPointerVelocityControl.reset();
5813 }
5814
5815 bool down;
5816 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5817#if DEBUG_GESTURES
5818 ALOGD("Gestures: TAP_DRAG");
5819#endif
5820 down = true;
5821 } else {
5822#if DEBUG_GESTURES
5823 ALOGD("Gestures: HOVER");
5824#endif
5825 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5826 *outFinishPreviousGesture = true;
5827 }
5828 mPointerGesture.activeGestureId = 0;
5829 down = false;
5830 }
5831
5832 float x, y;
5833 mPointerController->getPosition(&x, &y);
5834
5835 mPointerGesture.currentGestureIdBits.clear();
5836 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5837 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5838 mPointerGesture.currentGestureProperties[0].clear();
5839 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5840 mPointerGesture.currentGestureProperties[0].toolType =
5841 AMOTION_EVENT_TOOL_TYPE_FINGER;
5842 mPointerGesture.currentGestureCoords[0].clear();
5843 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5844 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5845 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5846 down ? 1.0f : 0.0f);
5847
5848 if (lastFingerCount == 0 && currentFingerCount != 0) {
5849 mPointerGesture.resetTap();
5850 mPointerGesture.tapDownTime = when;
5851 mPointerGesture.tapX = x;
5852 mPointerGesture.tapY = y;
5853 }
5854 } else {
5855 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5856 // We need to provide feedback for each finger that goes down so we cannot wait
5857 // for the fingers to move before deciding what to do.
5858 //
5859 // The ambiguous case is deciding what to do when there are two fingers down but they
5860 // have not moved enough to determine whether they are part of a drag or part of a
5861 // freeform gesture, or just a press or long-press at the pointer location.
5862 //
5863 // When there are two fingers we start with the PRESS hypothesis and we generate a
5864 // down at the pointer location.
5865 //
5866 // When the two fingers move enough or when additional fingers are added, we make
5867 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5868 ALOG_ASSERT(activeTouchId >= 0);
5869
5870 bool settled = when >= mPointerGesture.firstTouchTime
5871 + mConfig.pointerGestureMultitouchSettleInterval;
5872 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5873 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5874 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5875 *outFinishPreviousGesture = true;
5876 } else if (!settled && currentFingerCount > lastFingerCount) {
5877 // Additional pointers have gone down but not yet settled.
5878 // Reset the gesture.
5879#if DEBUG_GESTURES
5880 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5881 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5882 + mConfig.pointerGestureMultitouchSettleInterval - when)
5883 * 0.000001f);
5884#endif
5885 *outCancelPreviousGesture = true;
5886 } else {
5887 // Continue previous gesture.
5888 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5889 }
5890
5891 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5892 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5893 mPointerGesture.activeGestureId = 0;
5894 mPointerGesture.referenceIdBits.clear();
5895 mPointerVelocityControl.reset();
5896
5897 // Use the centroid and pointer location as the reference points for the gesture.
5898#if DEBUG_GESTURES
5899 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5900 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5901 + mConfig.pointerGestureMultitouchSettleInterval - when)
5902 * 0.000001f);
5903#endif
Michael Wright842500e2015-03-13 17:32:02 -07005904 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005905 &mPointerGesture.referenceTouchX,
5906 &mPointerGesture.referenceTouchY);
5907 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5908 &mPointerGesture.referenceGestureY);
5909 }
5910
5911 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005912 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005913 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5914 uint32_t id = idBits.clearFirstMarkedBit();
5915 mPointerGesture.referenceDeltas[id].dx = 0;
5916 mPointerGesture.referenceDeltas[id].dy = 0;
5917 }
Michael Wright842500e2015-03-13 17:32:02 -07005918 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005919
5920 // Add delta for all fingers and calculate a common movement delta.
5921 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005922 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5923 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005924 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5925 bool first = (idBits == commonIdBits);
5926 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005927 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5928 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5930 delta.dx += cpd.x - lpd.x;
5931 delta.dy += cpd.y - lpd.y;
5932
5933 if (first) {
5934 commonDeltaX = delta.dx;
5935 commonDeltaY = delta.dy;
5936 } else {
5937 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5938 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5939 }
5940 }
5941
5942 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5943 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5944 float dist[MAX_POINTER_ID + 1];
5945 int32_t distOverThreshold = 0;
5946 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5947 uint32_t id = idBits.clearFirstMarkedBit();
5948 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5949 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5950 delta.dy * mPointerYZoomScale);
5951 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5952 distOverThreshold += 1;
5953 }
5954 }
5955
5956 // Only transition when at least two pointers have moved further than
5957 // the minimum distance threshold.
5958 if (distOverThreshold >= 2) {
5959 if (currentFingerCount > 2) {
5960 // There are more than two pointers, switch to FREEFORM.
5961#if DEBUG_GESTURES
5962 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5963 currentFingerCount);
5964#endif
5965 *outCancelPreviousGesture = true;
5966 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5967 } else {
5968 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005969 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970 uint32_t id1 = idBits.clearFirstMarkedBit();
5971 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005972 const RawPointerData::Pointer& p1 =
5973 mCurrentRawState.rawPointerData.pointerForId(id1);
5974 const RawPointerData::Pointer& p2 =
5975 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5977 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5978 // There are two pointers but they are too far apart for a SWIPE,
5979 // switch to FREEFORM.
5980#if DEBUG_GESTURES
5981 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5982 mutualDistance, mPointerGestureMaxSwipeWidth);
5983#endif
5984 *outCancelPreviousGesture = true;
5985 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5986 } else {
5987 // There are two pointers. Wait for both pointers to start moving
5988 // before deciding whether this is a SWIPE or FREEFORM gesture.
5989 float dist1 = dist[id1];
5990 float dist2 = dist[id2];
5991 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5992 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5993 // Calculate the dot product of the displacement vectors.
5994 // When the vectors are oriented in approximately the same direction,
5995 // the angle betweeen them is near zero and the cosine of the angle
5996 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5997 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5998 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5999 float dx1 = delta1.dx * mPointerXZoomScale;
6000 float dy1 = delta1.dy * mPointerYZoomScale;
6001 float dx2 = delta2.dx * mPointerXZoomScale;
6002 float dy2 = delta2.dy * mPointerYZoomScale;
6003 float dot = dx1 * dx2 + dy1 * dy2;
6004 float cosine = dot / (dist1 * dist2); // denominator always > 0
6005 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6006 // Pointers are moving in the same direction. Switch to SWIPE.
6007#if DEBUG_GESTURES
6008 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6009 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6010 "cosine %0.3f >= %0.3f",
6011 dist1, mConfig.pointerGestureMultitouchMinDistance,
6012 dist2, mConfig.pointerGestureMultitouchMinDistance,
6013 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6014#endif
6015 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6016 } else {
6017 // Pointers are moving in different directions. Switch to FREEFORM.
6018#if DEBUG_GESTURES
6019 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6020 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6021 "cosine %0.3f < %0.3f",
6022 dist1, mConfig.pointerGestureMultitouchMinDistance,
6023 dist2, mConfig.pointerGestureMultitouchMinDistance,
6024 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6025#endif
6026 *outCancelPreviousGesture = true;
6027 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6028 }
6029 }
6030 }
6031 }
6032 }
6033 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6034 // Switch from SWIPE to FREEFORM if additional pointers go down.
6035 // Cancel previous gesture.
6036 if (currentFingerCount > 2) {
6037#if DEBUG_GESTURES
6038 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6039 currentFingerCount);
6040#endif
6041 *outCancelPreviousGesture = true;
6042 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6043 }
6044 }
6045
6046 // Move the reference points based on the overall group motion of the fingers
6047 // except in PRESS mode while waiting for a transition to occur.
6048 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6049 && (commonDeltaX || commonDeltaY)) {
6050 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6051 uint32_t id = idBits.clearFirstMarkedBit();
6052 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6053 delta.dx = 0;
6054 delta.dy = 0;
6055 }
6056
6057 mPointerGesture.referenceTouchX += commonDeltaX;
6058 mPointerGesture.referenceTouchY += commonDeltaY;
6059
6060 commonDeltaX *= mPointerXMovementScale;
6061 commonDeltaY *= mPointerYMovementScale;
6062
6063 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6064 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6065
6066 mPointerGesture.referenceGestureX += commonDeltaX;
6067 mPointerGesture.referenceGestureY += commonDeltaY;
6068 }
6069
6070 // Report gestures.
6071 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6072 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6073 // PRESS or SWIPE mode.
6074#if DEBUG_GESTURES
6075 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6076 "activeGestureId=%d, currentTouchPointerCount=%d",
6077 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6078#endif
6079 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6080
6081 mPointerGesture.currentGestureIdBits.clear();
6082 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6083 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6084 mPointerGesture.currentGestureProperties[0].clear();
6085 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6086 mPointerGesture.currentGestureProperties[0].toolType =
6087 AMOTION_EVENT_TOOL_TYPE_FINGER;
6088 mPointerGesture.currentGestureCoords[0].clear();
6089 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6090 mPointerGesture.referenceGestureX);
6091 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6092 mPointerGesture.referenceGestureY);
6093 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6094 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6095 // FREEFORM mode.
6096#if DEBUG_GESTURES
6097 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6098 "activeGestureId=%d, currentTouchPointerCount=%d",
6099 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6100#endif
6101 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6102
6103 mPointerGesture.currentGestureIdBits.clear();
6104
6105 BitSet32 mappedTouchIdBits;
6106 BitSet32 usedGestureIdBits;
6107 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6108 // Initially, assign the active gesture id to the active touch point
6109 // if there is one. No other touch id bits are mapped yet.
6110 if (!*outCancelPreviousGesture) {
6111 mappedTouchIdBits.markBit(activeTouchId);
6112 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6113 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6114 mPointerGesture.activeGestureId;
6115 } else {
6116 mPointerGesture.activeGestureId = -1;
6117 }
6118 } else {
6119 // Otherwise, assume we mapped all touches from the previous frame.
6120 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006121 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6122 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006123 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6124
6125 // Check whether we need to choose a new active gesture id because the
6126 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006127 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6128 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006129 !upTouchIdBits.isEmpty(); ) {
6130 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6131 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6132 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6133 mPointerGesture.activeGestureId = -1;
6134 break;
6135 }
6136 }
6137 }
6138
6139#if DEBUG_GESTURES
6140 ALOGD("Gestures: FREEFORM follow up "
6141 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6142 "activeGestureId=%d",
6143 mappedTouchIdBits.value, usedGestureIdBits.value,
6144 mPointerGesture.activeGestureId);
6145#endif
6146
Michael Wright842500e2015-03-13 17:32:02 -07006147 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006148 for (uint32_t i = 0; i < currentFingerCount; i++) {
6149 uint32_t touchId = idBits.clearFirstMarkedBit();
6150 uint32_t gestureId;
6151 if (!mappedTouchIdBits.hasBit(touchId)) {
6152 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6153 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6154#if DEBUG_GESTURES
6155 ALOGD("Gestures: FREEFORM "
6156 "new mapping for touch id %d -> gesture id %d",
6157 touchId, gestureId);
6158#endif
6159 } else {
6160 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6161#if DEBUG_GESTURES
6162 ALOGD("Gestures: FREEFORM "
6163 "existing mapping for touch id %d -> gesture id %d",
6164 touchId, gestureId);
6165#endif
6166 }
6167 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6168 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6169
6170 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006171 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006172 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6173 * mPointerXZoomScale;
6174 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6175 * mPointerYZoomScale;
6176 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6177
6178 mPointerGesture.currentGestureProperties[i].clear();
6179 mPointerGesture.currentGestureProperties[i].id = gestureId;
6180 mPointerGesture.currentGestureProperties[i].toolType =
6181 AMOTION_EVENT_TOOL_TYPE_FINGER;
6182 mPointerGesture.currentGestureCoords[i].clear();
6183 mPointerGesture.currentGestureCoords[i].setAxisValue(
6184 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6185 mPointerGesture.currentGestureCoords[i].setAxisValue(
6186 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6187 mPointerGesture.currentGestureCoords[i].setAxisValue(
6188 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6189 }
6190
6191 if (mPointerGesture.activeGestureId < 0) {
6192 mPointerGesture.activeGestureId =
6193 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6194#if DEBUG_GESTURES
6195 ALOGD("Gestures: FREEFORM new "
6196 "activeGestureId=%d", mPointerGesture.activeGestureId);
6197#endif
6198 }
6199 }
6200 }
6201
Michael Wright842500e2015-03-13 17:32:02 -07006202 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006203
6204#if DEBUG_GESTURES
6205 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6206 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6207 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6208 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6209 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6210 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6211 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6212 uint32_t id = idBits.clearFirstMarkedBit();
6213 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6214 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6215 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6216 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6217 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6218 id, index, properties.toolType,
6219 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6220 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6221 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6222 }
6223 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6224 uint32_t id = idBits.clearFirstMarkedBit();
6225 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6226 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6227 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6228 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6229 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6230 id, index, properties.toolType,
6231 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6232 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6233 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6234 }
6235#endif
6236 return true;
6237}
6238
6239void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6240 mPointerSimple.currentCoords.clear();
6241 mPointerSimple.currentProperties.clear();
6242
6243 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006244 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6245 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6246 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6247 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6248 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006249 mPointerController->setPosition(x, y);
6250
Michael Wright842500e2015-03-13 17:32:02 -07006251 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006252 down = !hovering;
6253
6254 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006255 mPointerSimple.currentCoords.copyFrom(
6256 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6258 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6259 mPointerSimple.currentProperties.id = 0;
6260 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006261 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 } else {
6263 down = false;
6264 hovering = false;
6265 }
6266
6267 dispatchPointerSimple(when, policyFlags, down, hovering);
6268}
6269
6270void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6271 abortPointerSimple(when, policyFlags);
6272}
6273
6274void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6275 mPointerSimple.currentCoords.clear();
6276 mPointerSimple.currentProperties.clear();
6277
6278 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006279 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6280 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6281 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006282 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006283 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6284 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006285 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006286 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006287 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006288 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006289 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290 * mPointerYMovementScale;
6291
6292 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6293 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6294
6295 mPointerController->move(deltaX, deltaY);
6296 } else {
6297 mPointerVelocityControl.reset();
6298 }
6299
Michael Wright842500e2015-03-13 17:32:02 -07006300 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006301 hovering = !down;
6302
6303 float x, y;
6304 mPointerController->getPosition(&x, &y);
6305 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006306 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006307 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6308 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6309 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6310 hovering ? 0.0f : 1.0f);
6311 mPointerSimple.currentProperties.id = 0;
6312 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006313 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 } else {
6315 mPointerVelocityControl.reset();
6316
6317 down = false;
6318 hovering = false;
6319 }
6320
6321 dispatchPointerSimple(when, policyFlags, down, hovering);
6322}
6323
6324void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6325 abortPointerSimple(when, policyFlags);
6326
6327 mPointerVelocityControl.reset();
6328}
6329
6330void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6331 bool down, bool hovering) {
6332 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006333 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334
Garfield Tan00f511d2019-06-12 16:55:40 -07006335 if (down || hovering) {
6336 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6337 mPointerController->clearSpots();
6338 mPointerController->setButtonState(mCurrentRawState.buttonState);
6339 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6340 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6341 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006343 displayId = mPointerController->getDisplayId();
6344
6345 float xCursorPosition;
6346 float yCursorPosition;
6347 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006348
6349 if (mPointerSimple.down && !down) {
6350 mPointerSimple.down = false;
6351
6352 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006353 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6354 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6355 mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006356 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6357 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6358 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6359 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 getListener()->notifyMotion(&args);
6361 }
6362
6363 if (mPointerSimple.hovering && !hovering) {
6364 mPointerSimple.hovering = false;
6365
6366 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006367 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6368 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6369 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006370 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6371 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6372 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6373 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006374 getListener()->notifyMotion(&args);
6375 }
6376
6377 if (down) {
6378 if (!mPointerSimple.down) {
6379 mPointerSimple.down = true;
6380 mPointerSimple.downTime = when;
6381
6382 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006383 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6384 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6385 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006386 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6387 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6388 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6389 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390 getListener()->notifyMotion(&args);
6391 }
6392
6393 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006394 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6395 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6396 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006397 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6398 &mPointerSimple.currentCoords, mOrientedXPrecision,
6399 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6400 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 getListener()->notifyMotion(&args);
6402 }
6403
6404 if (hovering) {
6405 if (!mPointerSimple.hovering) {
6406 mPointerSimple.hovering = true;
6407
6408 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006409 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6410 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6411 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006412 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6413 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6414 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6415 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 getListener()->notifyMotion(&args);
6417 }
6418
6419 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006420 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6421 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6422 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006423 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6424 &mPointerSimple.currentCoords, mOrientedXPrecision,
6425 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6426 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006427 getListener()->notifyMotion(&args);
6428 }
6429
Michael Wright842500e2015-03-13 17:32:02 -07006430 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6431 float vscroll = mCurrentRawState.rawVScroll;
6432 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006433 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6434 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435
6436 // Send scroll.
6437 PointerCoords pointerCoords;
6438 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6439 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6440 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6441
Garfield Tan00f511d2019-06-12 16:55:40 -07006442 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6443 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6444 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006445 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6446 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
6447 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6448 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006449 getListener()->notifyMotion(&args);
6450 }
6451
6452 // Save state.
6453 if (down || hovering) {
6454 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6455 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6456 } else {
6457 mPointerSimple.reset();
6458 }
6459}
6460
6461void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6462 mPointerSimple.currentCoords.clear();
6463 mPointerSimple.currentProperties.clear();
6464
6465 dispatchPointerSimple(when, policyFlags, false, false);
6466}
6467
6468void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006469 int32_t action, int32_t actionButton, int32_t flags,
6470 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6471 const PointerProperties* properties,
6472 const PointerCoords* coords, const uint32_t* idToIndex,
6473 BitSet32 idBits, int32_t changedId, float xPrecision,
6474 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475 PointerCoords pointerCoords[MAX_POINTERS];
6476 PointerProperties pointerProperties[MAX_POINTERS];
6477 uint32_t pointerCount = 0;
6478 while (!idBits.isEmpty()) {
6479 uint32_t id = idBits.clearFirstMarkedBit();
6480 uint32_t index = idToIndex[id];
6481 pointerProperties[pointerCount].copyFrom(properties[index]);
6482 pointerCoords[pointerCount].copyFrom(coords[index]);
6483
6484 if (changedId >= 0 && id == uint32_t(changedId)) {
6485 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6486 }
6487
6488 pointerCount += 1;
6489 }
6490
6491 ALOG_ASSERT(pointerCount != 0);
6492
6493 if (changedId >= 0 && pointerCount == 1) {
6494 // Replace initial down and final up action.
6495 // We can compare the action without masking off the changed pointer index
6496 // because we know the index is 0.
6497 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6498 action = AMOTION_EVENT_ACTION_DOWN;
6499 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6500 action = AMOTION_EVENT_ACTION_UP;
6501 } else {
6502 // Can't happen.
6503 ALOG_ASSERT(false);
6504 }
6505 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006506 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6507 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6508 if (mDeviceMode == DEVICE_MODE_POINTER) {
6509 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6510 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006511 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006512 const int32_t deviceId = getDeviceId();
6513 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006514 std::for_each(frames.begin(), frames.end(),
6515 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006516 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6517 policyFlags, action, actionButton, flags, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006518 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
6519 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
6520 downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006521 getListener()->notifyMotion(&args);
6522}
6523
6524bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6525 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6526 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6527 BitSet32 idBits) const {
6528 bool changed = false;
6529 while (!idBits.isEmpty()) {
6530 uint32_t id = idBits.clearFirstMarkedBit();
6531 uint32_t inIndex = inIdToIndex[id];
6532 uint32_t outIndex = outIdToIndex[id];
6533
6534 const PointerProperties& curInProperties = inProperties[inIndex];
6535 const PointerCoords& curInCoords = inCoords[inIndex];
6536 PointerProperties& curOutProperties = outProperties[outIndex];
6537 PointerCoords& curOutCoords = outCoords[outIndex];
6538
6539 if (curInProperties != curOutProperties) {
6540 curOutProperties.copyFrom(curInProperties);
6541 changed = true;
6542 }
6543
6544 if (curInCoords != curOutCoords) {
6545 curOutCoords.copyFrom(curInCoords);
6546 changed = true;
6547 }
6548 }
6549 return changed;
6550}
6551
6552void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006553 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006554 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6555 }
6556}
6557
Jeff Brownc9aa6282015-02-11 19:03:28 -08006558void TouchInputMapper::cancelTouch(nsecs_t when) {
6559 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006560 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006561}
6562
Michael Wrightd02c5b62014-02-10 15:10:22 -08006563bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006564 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006565 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006567 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6568 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6569 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570}
6571
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006572const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006573
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006574 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575#if DEBUG_VIRTUAL_KEYS
6576 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6577 "left=%d, top=%d, right=%d, bottom=%d",
6578 x, y,
6579 virtualKey.keyCode, virtualKey.scanCode,
6580 virtualKey.hitLeft, virtualKey.hitTop,
6581 virtualKey.hitRight, virtualKey.hitBottom);
6582#endif
6583
6584 if (virtualKey.isHit(x, y)) {
6585 return & virtualKey;
6586 }
6587 }
6588
Yi Kong9b14ac62018-07-17 13:48:38 -07006589 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006590}
6591
Michael Wright842500e2015-03-13 17:32:02 -07006592void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6593 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6594 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595
Michael Wright842500e2015-03-13 17:32:02 -07006596 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597
6598 if (currentPointerCount == 0) {
6599 // No pointers to assign.
6600 return;
6601 }
6602
6603 if (lastPointerCount == 0) {
6604 // All pointers are new.
6605 for (uint32_t i = 0; i < currentPointerCount; i++) {
6606 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006607 current->rawPointerData.pointers[i].id = id;
6608 current->rawPointerData.idToIndex[id] = i;
6609 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610 }
6611 return;
6612 }
6613
6614 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006615 && current->rawPointerData.pointers[0].toolType
6616 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006618 uint32_t id = last->rawPointerData.pointers[0].id;
6619 current->rawPointerData.pointers[0].id = id;
6620 current->rawPointerData.idToIndex[id] = 0;
6621 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006622 return;
6623 }
6624
6625 // General case.
6626 // We build a heap of squared euclidean distances between current and last pointers
6627 // associated with the current and last pointer indices. Then, we find the best
6628 // match (by distance) for each current pointer.
6629 // The pointers must have the same tool type but it is possible for them to
6630 // transition from hovering to touching or vice-versa while retaining the same id.
6631 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6632
6633 uint32_t heapSize = 0;
6634 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6635 currentPointerIndex++) {
6636 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6637 lastPointerIndex++) {
6638 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006639 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006641 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006642 if (currentPointer.toolType == lastPointer.toolType) {
6643 int64_t deltaX = currentPointer.x - lastPointer.x;
6644 int64_t deltaY = currentPointer.y - lastPointer.y;
6645
6646 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6647
6648 // Insert new element into the heap (sift up).
6649 heap[heapSize].currentPointerIndex = currentPointerIndex;
6650 heap[heapSize].lastPointerIndex = lastPointerIndex;
6651 heap[heapSize].distance = distance;
6652 heapSize += 1;
6653 }
6654 }
6655 }
6656
6657 // Heapify
6658 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6659 startIndex -= 1;
6660 for (uint32_t parentIndex = startIndex; ;) {
6661 uint32_t childIndex = parentIndex * 2 + 1;
6662 if (childIndex >= heapSize) {
6663 break;
6664 }
6665
6666 if (childIndex + 1 < heapSize
6667 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6668 childIndex += 1;
6669 }
6670
6671 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6672 break;
6673 }
6674
6675 swap(heap[parentIndex], heap[childIndex]);
6676 parentIndex = childIndex;
6677 }
6678 }
6679
6680#if DEBUG_POINTER_ASSIGNMENT
6681 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6682 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006683 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006684 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6685 heap[i].distance);
6686 }
6687#endif
6688
6689 // Pull matches out by increasing order of distance.
6690 // To avoid reassigning pointers that have already been matched, the loop keeps track
6691 // of which last and current pointers have been matched using the matchedXXXBits variables.
6692 // It also tracks the used pointer id bits.
6693 BitSet32 matchedLastBits(0);
6694 BitSet32 matchedCurrentBits(0);
6695 BitSet32 usedIdBits(0);
6696 bool first = true;
6697 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6698 while (heapSize > 0) {
6699 if (first) {
6700 // The first time through the loop, we just consume the root element of
6701 // the heap (the one with smallest distance).
6702 first = false;
6703 } else {
6704 // Previous iterations consumed the root element of the heap.
6705 // Pop root element off of the heap (sift down).
6706 heap[0] = heap[heapSize];
6707 for (uint32_t parentIndex = 0; ;) {
6708 uint32_t childIndex = parentIndex * 2 + 1;
6709 if (childIndex >= heapSize) {
6710 break;
6711 }
6712
6713 if (childIndex + 1 < heapSize
6714 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6715 childIndex += 1;
6716 }
6717
6718 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6719 break;
6720 }
6721
6722 swap(heap[parentIndex], heap[childIndex]);
6723 parentIndex = childIndex;
6724 }
6725
6726#if DEBUG_POINTER_ASSIGNMENT
6727 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6728 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006729 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006730 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6731 heap[i].distance);
6732 }
6733#endif
6734 }
6735
6736 heapSize -= 1;
6737
6738 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6739 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6740
6741 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6742 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6743
6744 matchedCurrentBits.markBit(currentPointerIndex);
6745 matchedLastBits.markBit(lastPointerIndex);
6746
Michael Wright842500e2015-03-13 17:32:02 -07006747 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6748 current->rawPointerData.pointers[currentPointerIndex].id = id;
6749 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6750 current->rawPointerData.markIdBit(id,
6751 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006752 usedIdBits.markBit(id);
6753
6754#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006755 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6756 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006757 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6758#endif
6759 break;
6760 }
6761 }
6762
6763 // Assign fresh ids to pointers that were not matched in the process.
6764 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6765 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6766 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6767
Michael Wright842500e2015-03-13 17:32:02 -07006768 current->rawPointerData.pointers[currentPointerIndex].id = id;
6769 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6770 current->rawPointerData.markIdBit(id,
6771 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006772
6773#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006774 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006775#endif
6776 }
6777}
6778
6779int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6780 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6781 return AKEY_STATE_VIRTUAL;
6782 }
6783
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006784 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006785 if (virtualKey.keyCode == keyCode) {
6786 return AKEY_STATE_UP;
6787 }
6788 }
6789
6790 return AKEY_STATE_UNKNOWN;
6791}
6792
6793int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6794 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6795 return AKEY_STATE_VIRTUAL;
6796 }
6797
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006798 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006799 if (virtualKey.scanCode == scanCode) {
6800 return AKEY_STATE_UP;
6801 }
6802 }
6803
6804 return AKEY_STATE_UNKNOWN;
6805}
6806
6807bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6808 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006809 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006810 for (size_t i = 0; i < numCodes; i++) {
6811 if (virtualKey.keyCode == keyCodes[i]) {
6812 outFlags[i] = 1;
6813 }
6814 }
6815 }
6816
6817 return true;
6818}
6819
Arthur Hungc23540e2018-11-29 20:42:11 +08006820std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6821 if (mParameters.hasAssociatedDisplay) {
6822 if (mDeviceMode == DEVICE_MODE_POINTER) {
6823 return std::make_optional(mPointerController->getDisplayId());
6824 } else {
6825 return std::make_optional(mViewport.displayId);
6826 }
6827 }
6828 return std::nullopt;
6829}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006830
6831// --- SingleTouchInputMapper ---
6832
6833SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6834 TouchInputMapper(device) {
6835}
6836
6837SingleTouchInputMapper::~SingleTouchInputMapper() {
6838}
6839
6840void SingleTouchInputMapper::reset(nsecs_t when) {
6841 mSingleTouchMotionAccumulator.reset(getDevice());
6842
6843 TouchInputMapper::reset(when);
6844}
6845
6846void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6847 TouchInputMapper::process(rawEvent);
6848
6849 mSingleTouchMotionAccumulator.process(rawEvent);
6850}
6851
Michael Wright842500e2015-03-13 17:32:02 -07006852void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006853 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006854 outState->rawPointerData.pointerCount = 1;
6855 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006856
6857 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6858 && (mTouchButtonAccumulator.isHovering()
6859 || (mRawPointerAxes.pressure.valid
6860 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006861 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006862
Michael Wright842500e2015-03-13 17:32:02 -07006863 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006864 outPointer.id = 0;
6865 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6866 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6867 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6868 outPointer.touchMajor = 0;
6869 outPointer.touchMinor = 0;
6870 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6871 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6872 outPointer.orientation = 0;
6873 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6874 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6875 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6876 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6877 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6878 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6879 }
6880 outPointer.isHovering = isHovering;
6881 }
6882}
6883
6884void SingleTouchInputMapper::configureRawPointerAxes() {
6885 TouchInputMapper::configureRawPointerAxes();
6886
6887 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6888 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6889 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6890 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6891 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6892 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6893 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6894}
6895
6896bool SingleTouchInputMapper::hasStylus() const {
6897 return mTouchButtonAccumulator.hasStylus();
6898}
6899
6900
6901// --- MultiTouchInputMapper ---
6902
6903MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6904 TouchInputMapper(device) {
6905}
6906
6907MultiTouchInputMapper::~MultiTouchInputMapper() {
6908}
6909
6910void MultiTouchInputMapper::reset(nsecs_t when) {
6911 mMultiTouchMotionAccumulator.reset(getDevice());
6912
6913 mPointerIdBits.clear();
6914
6915 TouchInputMapper::reset(when);
6916}
6917
6918void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6919 TouchInputMapper::process(rawEvent);
6920
6921 mMultiTouchMotionAccumulator.process(rawEvent);
6922}
6923
Michael Wright842500e2015-03-13 17:32:02 -07006924void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006925 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6926 size_t outCount = 0;
6927 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006928 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006929
6930 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6931 const MultiTouchMotionAccumulator::Slot* inSlot =
6932 mMultiTouchMotionAccumulator.getSlot(inIndex);
6933 if (!inSlot->isInUse()) {
6934 continue;
6935 }
6936
6937 if (outCount >= MAX_POINTERS) {
6938#if DEBUG_POINTERS
6939 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6940 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006941 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006942#endif
6943 break; // too many fingers!
6944 }
6945
Michael Wright842500e2015-03-13 17:32:02 -07006946 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947 outPointer.x = inSlot->getX();
6948 outPointer.y = inSlot->getY();
6949 outPointer.pressure = inSlot->getPressure();
6950 outPointer.touchMajor = inSlot->getTouchMajor();
6951 outPointer.touchMinor = inSlot->getTouchMinor();
6952 outPointer.toolMajor = inSlot->getToolMajor();
6953 outPointer.toolMinor = inSlot->getToolMinor();
6954 outPointer.orientation = inSlot->getOrientation();
6955 outPointer.distance = inSlot->getDistance();
6956 outPointer.tiltX = 0;
6957 outPointer.tiltY = 0;
6958
6959 outPointer.toolType = inSlot->getToolType();
6960 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6961 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6962 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6963 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6964 }
6965 }
6966
6967 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6968 && (mTouchButtonAccumulator.isHovering()
6969 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6970 outPointer.isHovering = isHovering;
6971
6972 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006973 if (mHavePointerIds) {
6974 int32_t trackingId = inSlot->getTrackingId();
6975 int32_t id = -1;
6976 if (trackingId >= 0) {
6977 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6978 uint32_t n = idBits.clearFirstMarkedBit();
6979 if (mPointerTrackingIdMap[n] == trackingId) {
6980 id = n;
6981 }
6982 }
6983
6984 if (id < 0 && !mPointerIdBits.isFull()) {
6985 id = mPointerIdBits.markFirstUnmarkedBit();
6986 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006987 }
Michael Wright842500e2015-03-13 17:32:02 -07006988 }
gaoshang1a632de2016-08-24 10:23:50 +08006989 if (id < 0) {
6990 mHavePointerIds = false;
6991 outState->rawPointerData.clearIdBits();
6992 newPointerIdBits.clear();
6993 } else {
6994 outPointer.id = id;
6995 outState->rawPointerData.idToIndex[id] = outCount;
6996 outState->rawPointerData.markIdBit(id, isHovering);
6997 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006998 }
Michael Wright842500e2015-03-13 17:32:02 -07006999 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007000 outCount += 1;
7001 }
7002
Michael Wright842500e2015-03-13 17:32:02 -07007003 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007004 mPointerIdBits = newPointerIdBits;
7005
7006 mMultiTouchMotionAccumulator.finishSync();
7007}
7008
7009void MultiTouchInputMapper::configureRawPointerAxes() {
7010 TouchInputMapper::configureRawPointerAxes();
7011
7012 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7013 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7014 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7015 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7016 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7017 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7018 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7019 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7020 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7021 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7022 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7023
7024 if (mRawPointerAxes.trackingId.valid
7025 && mRawPointerAxes.slot.valid
7026 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7027 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7028 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007029 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7030 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007031 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007032 slotCount = MAX_SLOTS;
7033 }
7034 mMultiTouchMotionAccumulator.configure(getDevice(),
7035 slotCount, true /*usingSlotsProtocol*/);
7036 } else {
7037 mMultiTouchMotionAccumulator.configure(getDevice(),
7038 MAX_POINTERS, false /*usingSlotsProtocol*/);
7039 }
7040}
7041
7042bool MultiTouchInputMapper::hasStylus() const {
7043 return mMultiTouchMotionAccumulator.hasStylus()
7044 || mTouchButtonAccumulator.hasStylus();
7045}
7046
Michael Wright842500e2015-03-13 17:32:02 -07007047// --- ExternalStylusInputMapper
7048
7049ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7050 InputMapper(device) {
7051
7052}
7053
7054uint32_t ExternalStylusInputMapper::getSources() {
7055 return AINPUT_SOURCE_STYLUS;
7056}
7057
7058void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7059 InputMapper::populateDeviceInfo(info);
7060 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7061 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7062}
7063
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007064void ExternalStylusInputMapper::dump(std::string& dump) {
7065 dump += INDENT2 "External Stylus Input Mapper:\n";
7066 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007067 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007068 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007069 dumpStylusState(dump, mStylusState);
7070}
7071
7072void ExternalStylusInputMapper::configure(nsecs_t when,
7073 const InputReaderConfiguration* config, uint32_t changes) {
7074 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7075 mTouchButtonAccumulator.configure(getDevice());
7076}
7077
7078void ExternalStylusInputMapper::reset(nsecs_t when) {
7079 InputDevice* device = getDevice();
7080 mSingleTouchMotionAccumulator.reset(device);
7081 mTouchButtonAccumulator.reset(device);
7082 InputMapper::reset(when);
7083}
7084
7085void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7086 mSingleTouchMotionAccumulator.process(rawEvent);
7087 mTouchButtonAccumulator.process(rawEvent);
7088
7089 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7090 sync(rawEvent->when);
7091 }
7092}
7093
7094void ExternalStylusInputMapper::sync(nsecs_t when) {
7095 mStylusState.clear();
7096
7097 mStylusState.when = when;
7098
Michael Wright45ccacf2015-04-21 19:01:58 +01007099 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7100 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7101 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7102 }
7103
Michael Wright842500e2015-03-13 17:32:02 -07007104 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7105 if (mRawPressureAxis.valid) {
7106 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7107 } else if (mTouchButtonAccumulator.isToolActive()) {
7108 mStylusState.pressure = 1.0f;
7109 } else {
7110 mStylusState.pressure = 0.0f;
7111 }
7112
7113 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007114
7115 mContext->dispatchExternalStylusState(mStylusState);
7116}
7117
Michael Wrightd02c5b62014-02-10 15:10:22 -08007118
7119// --- JoystickInputMapper ---
7120
7121JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7122 InputMapper(device) {
7123}
7124
7125JoystickInputMapper::~JoystickInputMapper() {
7126}
7127
7128uint32_t JoystickInputMapper::getSources() {
7129 return AINPUT_SOURCE_JOYSTICK;
7130}
7131
7132void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7133 InputMapper::populateDeviceInfo(info);
7134
7135 for (size_t i = 0; i < mAxes.size(); i++) {
7136 const Axis& axis = mAxes.valueAt(i);
7137 addMotionRange(axis.axisInfo.axis, axis, info);
7138
7139 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7140 addMotionRange(axis.axisInfo.highAxis, axis, info);
7141
7142 }
7143 }
7144}
7145
7146void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7147 InputDeviceInfo* info) {
7148 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7149 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7150 /* In order to ease the transition for developers from using the old axes
7151 * to the newer, more semantically correct axes, we'll continue to register
7152 * the old axes as duplicates of their corresponding new ones. */
7153 int32_t compatAxis = getCompatAxis(axisId);
7154 if (compatAxis >= 0) {
7155 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7156 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7157 }
7158}
7159
7160/* A mapping from axes the joystick actually has to the axes that should be
7161 * artificially created for compatibility purposes.
7162 * Returns -1 if no compatibility axis is needed. */
7163int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7164 switch(axis) {
7165 case AMOTION_EVENT_AXIS_LTRIGGER:
7166 return AMOTION_EVENT_AXIS_BRAKE;
7167 case AMOTION_EVENT_AXIS_RTRIGGER:
7168 return AMOTION_EVENT_AXIS_GAS;
7169 }
7170 return -1;
7171}
7172
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007173void JoystickInputMapper::dump(std::string& dump) {
7174 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007175
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007176 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007177 size_t numAxes = mAxes.size();
7178 for (size_t i = 0; i < numAxes; i++) {
7179 const Axis& axis = mAxes.valueAt(i);
7180 const char* label = getAxisLabel(axis.axisInfo.axis);
7181 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007182 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007184 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007185 }
7186 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7187 label = getAxisLabel(axis.axisInfo.highAxis);
7188 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007189 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007190 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007191 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007192 axis.axisInfo.splitValue);
7193 }
7194 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007195 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007196 }
7197
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007198 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 -08007199 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007200 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007201 "highScale=%0.5f, highOffset=%0.5f\n",
7202 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007203 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007204 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7205 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7206 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7207 }
7208}
7209
7210void JoystickInputMapper::configure(nsecs_t when,
7211 const InputReaderConfiguration* config, uint32_t changes) {
7212 InputMapper::configure(when, config, changes);
7213
7214 if (!changes) { // first time only
7215 // Collect all axes.
7216 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7217 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7218 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7219 continue; // axis must be claimed by a different device
7220 }
7221
7222 RawAbsoluteAxisInfo rawAxisInfo;
7223 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7224 if (rawAxisInfo.valid) {
7225 // Map axis.
7226 AxisInfo axisInfo;
7227 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7228 if (!explicitlyMapped) {
7229 // Axis is not explicitly mapped, will choose a generic axis later.
7230 axisInfo.mode = AxisInfo::MODE_NORMAL;
7231 axisInfo.axis = -1;
7232 }
7233
7234 // Apply flat override.
7235 int32_t rawFlat = axisInfo.flatOverride < 0
7236 ? rawAxisInfo.flat : axisInfo.flatOverride;
7237
7238 // Calculate scaling factors and limits.
7239 Axis axis;
7240 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7241 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7242 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7243 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7244 scale, 0.0f, highScale, 0.0f,
7245 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7246 rawAxisInfo.resolution * scale);
7247 } else if (isCenteredAxis(axisInfo.axis)) {
7248 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7249 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7250 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7251 scale, offset, scale, offset,
7252 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7253 rawAxisInfo.resolution * scale);
7254 } else {
7255 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7256 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7257 scale, 0.0f, scale, 0.0f,
7258 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7259 rawAxisInfo.resolution * scale);
7260 }
7261
7262 // To eliminate noise while the joystick is at rest, filter out small variations
7263 // in axis values up front.
7264 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7265
7266 mAxes.add(abs, axis);
7267 }
7268 }
7269
7270 // If there are too many axes, start dropping them.
7271 // Prefer to keep explicitly mapped axes.
7272 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007273 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007274 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007275 pruneAxes(true);
7276 pruneAxes(false);
7277 }
7278
7279 // Assign generic axis ids to remaining axes.
7280 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7281 size_t numAxes = mAxes.size();
7282 for (size_t i = 0; i < numAxes; i++) {
7283 Axis& axis = mAxes.editValueAt(i);
7284 if (axis.axisInfo.axis < 0) {
7285 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7286 && haveAxis(nextGenericAxisId)) {
7287 nextGenericAxisId += 1;
7288 }
7289
7290 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7291 axis.axisInfo.axis = nextGenericAxisId;
7292 nextGenericAxisId += 1;
7293 } else {
7294 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7295 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007296 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007297 mAxes.removeItemsAt(i--);
7298 numAxes -= 1;
7299 }
7300 }
7301 }
7302 }
7303}
7304
7305bool JoystickInputMapper::haveAxis(int32_t axisId) {
7306 size_t numAxes = mAxes.size();
7307 for (size_t i = 0; i < numAxes; i++) {
7308 const Axis& axis = mAxes.valueAt(i);
7309 if (axis.axisInfo.axis == axisId
7310 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7311 && axis.axisInfo.highAxis == axisId)) {
7312 return true;
7313 }
7314 }
7315 return false;
7316}
7317
7318void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7319 size_t i = mAxes.size();
7320 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7321 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7322 continue;
7323 }
7324 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007325 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007326 mAxes.removeItemsAt(i);
7327 }
7328}
7329
7330bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7331 switch (axis) {
7332 case AMOTION_EVENT_AXIS_X:
7333 case AMOTION_EVENT_AXIS_Y:
7334 case AMOTION_EVENT_AXIS_Z:
7335 case AMOTION_EVENT_AXIS_RX:
7336 case AMOTION_EVENT_AXIS_RY:
7337 case AMOTION_EVENT_AXIS_RZ:
7338 case AMOTION_EVENT_AXIS_HAT_X:
7339 case AMOTION_EVENT_AXIS_HAT_Y:
7340 case AMOTION_EVENT_AXIS_ORIENTATION:
7341 case AMOTION_EVENT_AXIS_RUDDER:
7342 case AMOTION_EVENT_AXIS_WHEEL:
7343 return true;
7344 default:
7345 return false;
7346 }
7347}
7348
7349void JoystickInputMapper::reset(nsecs_t when) {
7350 // Recenter all axes.
7351 size_t numAxes = mAxes.size();
7352 for (size_t i = 0; i < numAxes; i++) {
7353 Axis& axis = mAxes.editValueAt(i);
7354 axis.resetValue();
7355 }
7356
7357 InputMapper::reset(when);
7358}
7359
7360void JoystickInputMapper::process(const RawEvent* rawEvent) {
7361 switch (rawEvent->type) {
7362 case EV_ABS: {
7363 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7364 if (index >= 0) {
7365 Axis& axis = mAxes.editValueAt(index);
7366 float newValue, highNewValue;
7367 switch (axis.axisInfo.mode) {
7368 case AxisInfo::MODE_INVERT:
7369 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7370 * axis.scale + axis.offset;
7371 highNewValue = 0.0f;
7372 break;
7373 case AxisInfo::MODE_SPLIT:
7374 if (rawEvent->value < axis.axisInfo.splitValue) {
7375 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7376 * axis.scale + axis.offset;
7377 highNewValue = 0.0f;
7378 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7379 newValue = 0.0f;
7380 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7381 * axis.highScale + axis.highOffset;
7382 } else {
7383 newValue = 0.0f;
7384 highNewValue = 0.0f;
7385 }
7386 break;
7387 default:
7388 newValue = rawEvent->value * axis.scale + axis.offset;
7389 highNewValue = 0.0f;
7390 break;
7391 }
7392 axis.newValue = newValue;
7393 axis.highNewValue = highNewValue;
7394 }
7395 break;
7396 }
7397
7398 case EV_SYN:
7399 switch (rawEvent->code) {
7400 case SYN_REPORT:
7401 sync(rawEvent->when, false /*force*/);
7402 break;
7403 }
7404 break;
7405 }
7406}
7407
7408void JoystickInputMapper::sync(nsecs_t when, bool force) {
7409 if (!filterAxes(force)) {
7410 return;
7411 }
7412
7413 int32_t metaState = mContext->getGlobalMetaState();
7414 int32_t buttonState = 0;
7415
7416 PointerProperties pointerProperties;
7417 pointerProperties.clear();
7418 pointerProperties.id = 0;
7419 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7420
7421 PointerCoords pointerCoords;
7422 pointerCoords.clear();
7423
7424 size_t numAxes = mAxes.size();
7425 for (size_t i = 0; i < numAxes; i++) {
7426 const Axis& axis = mAxes.valueAt(i);
7427 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7428 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7429 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7430 axis.highCurrentValue);
7431 }
7432 }
7433
7434 // Moving a joystick axis should not wake the device because joysticks can
7435 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7436 // button will likely wake the device.
7437 // TODO: Use the input device configuration to control this behavior more finely.
7438 uint32_t policyFlags = 0;
7439
Prabir Pradhan42611e02018-11-27 14:04:02 -08007440 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007441 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7442 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07007443 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
7444 &pointerProperties, &pointerCoords, 0, 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07007445 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7446 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007447 getListener()->notifyMotion(&args);
7448}
7449
7450void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7451 int32_t axis, float value) {
7452 pointerCoords->setAxisValue(axis, value);
7453 /* In order to ease the transition for developers from using the old axes
7454 * to the newer, more semantically correct axes, we'll continue to produce
7455 * values for the old axes as mirrors of the value of their corresponding
7456 * new axes. */
7457 int32_t compatAxis = getCompatAxis(axis);
7458 if (compatAxis >= 0) {
7459 pointerCoords->setAxisValue(compatAxis, value);
7460 }
7461}
7462
7463bool JoystickInputMapper::filterAxes(bool force) {
7464 bool atLeastOneSignificantChange = force;
7465 size_t numAxes = mAxes.size();
7466 for (size_t i = 0; i < numAxes; i++) {
7467 Axis& axis = mAxes.editValueAt(i);
7468 if (force || hasValueChangedSignificantly(axis.filter,
7469 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7470 axis.currentValue = axis.newValue;
7471 atLeastOneSignificantChange = true;
7472 }
7473 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7474 if (force || hasValueChangedSignificantly(axis.filter,
7475 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7476 axis.highCurrentValue = axis.highNewValue;
7477 atLeastOneSignificantChange = true;
7478 }
7479 }
7480 }
7481 return atLeastOneSignificantChange;
7482}
7483
7484bool JoystickInputMapper::hasValueChangedSignificantly(
7485 float filter, float newValue, float currentValue, float min, float max) {
7486 if (newValue != currentValue) {
7487 // Filter out small changes in value unless the value is converging on the axis
7488 // bounds or center point. This is intended to reduce the amount of information
7489 // sent to applications by particularly noisy joysticks (such as PS3).
7490 if (fabs(newValue - currentValue) > filter
7491 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7492 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7493 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7494 return true;
7495 }
7496 }
7497 return false;
7498}
7499
7500bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7501 float filter, float newValue, float currentValue, float thresholdValue) {
7502 float newDistance = fabs(newValue - thresholdValue);
7503 if (newDistance < filter) {
7504 float oldDistance = fabs(currentValue - thresholdValue);
7505 if (newDistance < oldDistance) {
7506 return true;
7507 }
7508 }
7509 return false;
7510}
7511
7512} // namespace android