blob: 9e5990964c7be993c344a3871b0ea970eb2c447a [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>
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080060#include <statslog.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66#define INDENT5 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// --- Constants ---
73
74// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080075static constexpr size_t MAX_SLOTS = 32;
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Michael Wright842500e2015-03-13 17:32:02 -070077// Maximum amount of latency to add to touch events while waiting for data from an
78// external stylus.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080079static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070080
Michael Wright43fd19f2015-04-21 19:02:58 +010081// Maximum amount of time to wait on touch data before pushing out new pressure data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080082static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
Michael Wright43fd19f2015-04-21 19:02:58 +010083
84// Artificial latency on synthetic events created from stylus data without corresponding touch
85// data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080086static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
87
88// How often to report input event statistics
89static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60);
Michael Wright43fd19f2015-04-21 19:02:58 +010090
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// --- Static Functions ---
92
93template<typename T>
94inline static T abs(const T& value) {
95 return value < 0 ? - value : value;
96}
97
98template<typename T>
99inline static T min(const T& a, const T& b) {
100 return a < b ? a : b;
101}
102
103template<typename T>
104inline static void swap(T& a, T& b) {
105 T temp = a;
106 a = b;
107 b = temp;
108}
109
110inline static float avg(float x, float y) {
111 return (x + y) / 2;
112}
113
114inline static float distance(float x1, float y1, float x2, float y2) {
115 return hypotf(x1 - x2, y1 - y2);
116}
117
118inline static int32_t signExtendNybble(int32_t value) {
119 return value >= 8 ? value - 16 : value;
120}
121
122static inline const char* toString(bool value) {
123 return value ? "true" : "false";
124}
125
126static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
127 const int32_t map[][4], size_t mapSize) {
128 if (orientation != DISPLAY_ORIENTATION_0) {
129 for (size_t i = 0; i < mapSize; i++) {
130 if (value == map[i][0]) {
131 return map[i][orientation];
132 }
133 }
134 }
135 return value;
136}
137
138static const int32_t keyCodeRotationMap[][4] = {
139 // key codes enumerated counter-clockwise with the original (unrotated) key first
140 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
141 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
142 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
143 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
144 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700145 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
146 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
147 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
148 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
149 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
150 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
151 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
152 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153};
154static const size_t keyCodeRotationMapSize =
155 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
156
Ivan Podogovb9afef32017-02-13 15:34:32 +0000157static int32_t rotateStemKey(int32_t value, int32_t orientation,
158 const int32_t map[][2], size_t mapSize) {
159 if (orientation == DISPLAY_ORIENTATION_180) {
160 for (size_t i = 0; i < mapSize; i++) {
161 if (value == map[i][0]) {
162 return map[i][1];
163 }
164 }
165 }
166 return value;
167}
168
169// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
170static int32_t stemKeyRotationMap[][2] = {
171 // key codes enumerated with the original (unrotated) key first
172 // no rotation, 180 degree rotation
173 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
174 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
175 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
176 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
177};
178static const size_t stemKeyRotationMapSize =
179 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
180
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000182 keyCode = rotateStemKey(keyCode, orientation,
183 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return rotateValueUsingRotationMap(keyCode, orientation,
185 keyCodeRotationMap, keyCodeRotationMapSize);
186}
187
188static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
189 float temp;
190 switch (orientation) {
191 case DISPLAY_ORIENTATION_90:
192 temp = *deltaX;
193 *deltaX = *deltaY;
194 *deltaY = -temp;
195 break;
196
197 case DISPLAY_ORIENTATION_180:
198 *deltaX = -*deltaX;
199 *deltaY = -*deltaY;
200 break;
201
202 case DISPLAY_ORIENTATION_270:
203 temp = *deltaX;
204 *deltaX = -*deltaY;
205 *deltaY = temp;
206 break;
207 }
208}
209
210static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
211 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
212}
213
214// Returns true if the pointer should be reported as being down given the specified
215// button states. This determines whether the event is reported as a touch event.
216static bool isPointerDown(int32_t buttonState) {
217 return buttonState &
218 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
219 | AMOTION_EVENT_BUTTON_TERTIARY);
220}
221
222static float calculateCommonVector(float a, float b) {
223 if (a > 0 && b > 0) {
224 return a < b ? a : b;
225 } else if (a < 0 && b < 0) {
226 return a > b ? a : b;
227 } else {
228 return 0;
229 }
230}
231
232static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100233 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
235 int32_t buttonState, int32_t keyCode) {
236 if (
237 (action == AKEY_EVENT_ACTION_DOWN
238 && !(lastButtonState & buttonState)
239 && (currentButtonState & buttonState))
240 || (action == AKEY_EVENT_ACTION_UP
241 && (lastButtonState & buttonState)
242 && !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800243 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
244 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 context->getListener()->notifyKey(&args);
246 }
247}
248
249static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100250 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100252 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 lastButtonState, currentButtonState,
254 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100255 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 lastButtonState, currentButtonState,
257 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
258}
259
260
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261// --- InputReader ---
262
263InputReader::InputReader(const sp<EventHubInterface>& eventHub,
264 const sp<InputReaderPolicyInterface>& policy,
265 const sp<InputListenerInterface>& listener) :
266 mContext(this), mEventHub(eventHub), mPolicy(policy),
Prabir Pradhan42611e02018-11-27 14:04:02 -0800267 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
269 mConfigurationChangesToRefresh(0) {
270 mQueuedListener = new QueuedInputListener(listener);
271
272 { // acquire lock
273 AutoMutex _l(mLock);
274
275 refreshConfigurationLocked(0);
276 updateGlobalMetaStateLocked();
277 } // release lock
278}
279
280InputReader::~InputReader() {
281 for (size_t i = 0; i < mDevices.size(); i++) {
282 delete mDevices.valueAt(i);
283 }
284}
285
286void InputReader::loopOnce() {
287 int32_t oldGeneration;
288 int32_t timeoutMillis;
289 bool inputDevicesChanged = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800290 std::vector<InputDeviceInfo> inputDevices;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291 { // acquire lock
292 AutoMutex _l(mLock);
293
294 oldGeneration = mGeneration;
295 timeoutMillis = -1;
296
297 uint32_t changes = mConfigurationChangesToRefresh;
298 if (changes) {
299 mConfigurationChangesToRefresh = 0;
300 timeoutMillis = 0;
301 refreshConfigurationLocked(changes);
302 } else if (mNextTimeout != LLONG_MAX) {
303 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
304 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
305 }
306 } // release lock
307
308 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
309
310 { // acquire lock
311 AutoMutex _l(mLock);
312 mReaderIsAliveCondition.broadcast();
313
314 if (count) {
315 processEventsLocked(mEventBuffer, count);
316 }
317
318 if (mNextTimeout != LLONG_MAX) {
319 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320 if (now >= mNextTimeout) {
321#if DEBUG_RAW_EVENTS
322 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
323#endif
324 mNextTimeout = LLONG_MAX;
325 timeoutExpiredLocked(now);
326 }
327 }
328
329 if (oldGeneration != mGeneration) {
330 inputDevicesChanged = true;
331 getInputDevicesLocked(inputDevices);
332 }
333 } // release lock
334
335 // Send out a message that the describes the changed input devices.
336 if (inputDevicesChanged) {
337 mPolicy->notifyInputDevicesChanged(inputDevices);
338 }
339
340 // Flush queued events out to the listener.
341 // This must happen outside of the lock because the listener could potentially call
342 // back into the InputReader's methods, such as getScanCodeState, or become blocked
343 // on another thread similarly waiting to acquire the InputReader lock thereby
344 // resulting in a deadlock. This situation is actually quite plausible because the
345 // listener is actually the input dispatcher, which calls into the window manager,
346 // which occasionally calls into the input reader.
347 mQueuedListener->flush();
348}
349
350void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
351 for (const RawEvent* rawEvent = rawEvents; count;) {
352 int32_t type = rawEvent->type;
353 size_t batchSize = 1;
354 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
355 int32_t deviceId = rawEvent->deviceId;
356 while (batchSize < count) {
357 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
358 || rawEvent[batchSize].deviceId != deviceId) {
359 break;
360 }
361 batchSize += 1;
362 }
363#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700364 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365#endif
366 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
367 } else {
368 switch (rawEvent->type) {
369 case EventHubInterface::DEVICE_ADDED:
370 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::DEVICE_REMOVED:
373 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
374 break;
375 case EventHubInterface::FINISHED_DEVICE_SCAN:
376 handleConfigurationChangedLocked(rawEvent->when);
377 break;
378 default:
379 ALOG_ASSERT(false); // can't happen
380 break;
381 }
382 }
383 count -= batchSize;
384 rawEvent += batchSize;
385 }
386}
387
388void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
389 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
390 if (deviceIndex >= 0) {
391 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
392 return;
393 }
394
395 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
396 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
397 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
398
399 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
400 device->configure(when, &mConfig, 0);
401 device->reset(when);
402
403 if (device->isIgnored()) {
404 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100405 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 } else {
407 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100408 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 }
410
411 mDevices.add(deviceId, device);
412 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700413
414 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
415 notifyExternalStylusPresenceChanged();
416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417}
418
419void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700420 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
422 if (deviceIndex < 0) {
423 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
424 return;
425 }
426
427 device = mDevices.valueAt(deviceIndex);
428 mDevices.removeItemsAt(deviceIndex, 1);
429 bumpGenerationLocked();
430
431 if (device->isIgnored()) {
432 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100433 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 } else {
435 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100436 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 }
438
Michael Wright842500e2015-03-13 17:32:02 -0700439 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
440 notifyExternalStylusPresenceChanged();
441 }
442
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 device->reset(when);
444 delete device;
445}
446
447InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
448 const InputDeviceIdentifier& identifier, uint32_t classes) {
449 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
450 controllerNumber, identifier, classes);
451
452 // External devices.
453 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
454 device->setExternal(true);
455 }
456
Tim Kilbourn063ff532015-04-08 10:26:18 -0700457 // Devices with mics.
458 if (classes & INPUT_DEVICE_CLASS_MIC) {
459 device->setMic(true);
460 }
461
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 // Switch-like devices.
463 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
464 device->addMapper(new SwitchInputMapper(device));
465 }
466
Prashant Malani1941ff52015-08-11 18:29:28 -0700467 // Scroll wheel-like devices.
468 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
469 device->addMapper(new RotaryEncoderInputMapper(device));
470 }
471
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 // Vibrator-like devices.
473 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
474 device->addMapper(new VibratorInputMapper(device));
475 }
476
477 // Keyboard-like devices.
478 uint32_t keyboardSource = 0;
479 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
480 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
481 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
482 }
483 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
484 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
485 }
486 if (classes & INPUT_DEVICE_CLASS_DPAD) {
487 keyboardSource |= AINPUT_SOURCE_DPAD;
488 }
489 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
490 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
491 }
492
493 if (keyboardSource != 0) {
494 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
495 }
496
497 // Cursor-like devices.
498 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
499 device->addMapper(new CursorInputMapper(device));
500 }
501
502 // Touchscreens and touchpad devices.
503 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
504 device->addMapper(new MultiTouchInputMapper(device));
505 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
506 device->addMapper(new SingleTouchInputMapper(device));
507 }
508
509 // Joystick-like devices.
510 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
511 device->addMapper(new JoystickInputMapper(device));
512 }
513
Michael Wright842500e2015-03-13 17:32:02 -0700514 // External stylus-like devices.
515 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
516 device->addMapper(new ExternalStylusInputMapper(device));
517 }
518
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 return device;
520}
521
522void InputReader::processEventsForDeviceLocked(int32_t deviceId,
523 const RawEvent* rawEvents, size_t count) {
524 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
525 if (deviceIndex < 0) {
526 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
527 return;
528 }
529
530 InputDevice* device = mDevices.valueAt(deviceIndex);
531 if (device->isIgnored()) {
532 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
533 return;
534 }
535
536 device->process(rawEvents, count);
537}
538
539void InputReader::timeoutExpiredLocked(nsecs_t when) {
540 for (size_t i = 0; i < mDevices.size(); i++) {
541 InputDevice* device = mDevices.valueAt(i);
542 if (!device->isIgnored()) {
543 device->timeoutExpired(when);
544 }
545 }
546}
547
548void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
549 // Reset global meta state because it depends on the list of all configured devices.
550 updateGlobalMetaStateLocked();
551
552 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800553 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 mQueuedListener->notifyConfigurationChanged(&args);
555}
556
557void InputReader::refreshConfigurationLocked(uint32_t changes) {
558 mPolicy->getReaderConfiguration(&mConfig);
559 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
560
561 if (changes) {
562 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
563 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
564
565 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
566 mEventHub->requestReopenDevices();
567 } else {
568 for (size_t i = 0; i < mDevices.size(); i++) {
569 InputDevice* device = mDevices.valueAt(i);
570 device->configure(now, &mConfig, changes);
571 }
572 }
573 }
574}
575
576void InputReader::updateGlobalMetaStateLocked() {
577 mGlobalMetaState = 0;
578
579 for (size_t i = 0; i < mDevices.size(); i++) {
580 InputDevice* device = mDevices.valueAt(i);
581 mGlobalMetaState |= device->getMetaState();
582 }
583}
584
585int32_t InputReader::getGlobalMetaStateLocked() {
586 return mGlobalMetaState;
587}
588
Michael Wright842500e2015-03-13 17:32:02 -0700589void InputReader::notifyExternalStylusPresenceChanged() {
590 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
591}
592
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800593void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700594 for (size_t i = 0; i < mDevices.size(); i++) {
595 InputDevice* device = mDevices.valueAt(i);
596 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800597 InputDeviceInfo info;
598 device->getDeviceInfo(&info);
599 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700600 }
601 }
602}
603
604void InputReader::dispatchExternalStylusState(const StylusState& state) {
605 for (size_t i = 0; i < mDevices.size(); i++) {
606 InputDevice* device = mDevices.valueAt(i);
607 device->updateExternalStylusState(state);
608 }
609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
612 mDisableVirtualKeysTimeout = time;
613}
614
615bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
616 InputDevice* device, int32_t keyCode, int32_t scanCode) {
617 if (now < mDisableVirtualKeysTimeout) {
618 ALOGI("Dropping virtual key from device %s because virtual keys are "
619 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100620 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 (mDisableVirtualKeysTimeout - now) * 0.000001,
622 keyCode, scanCode);
623 return true;
624 } else {
625 return false;
626 }
627}
628
629void InputReader::fadePointerLocked() {
630 for (size_t i = 0; i < mDevices.size(); i++) {
631 InputDevice* device = mDevices.valueAt(i);
632 device->fadePointer();
633 }
634}
635
636void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
637 if (when < mNextTimeout) {
638 mNextTimeout = when;
639 mEventHub->wake();
640 }
641}
642
643int32_t InputReader::bumpGenerationLocked() {
644 return ++mGeneration;
645}
646
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800647void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 AutoMutex _l(mLock);
649 getInputDevicesLocked(outInputDevices);
650}
651
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800652void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 outInputDevices.clear();
654
655 size_t numDevices = mDevices.size();
656 for (size_t i = 0; i < numDevices; i++) {
657 InputDevice* device = mDevices.valueAt(i);
658 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800659 InputDeviceInfo info;
660 device->getDeviceInfo(&info);
661 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 }
663 }
664}
665
666int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
667 int32_t keyCode) {
668 AutoMutex _l(mLock);
669
670 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
671}
672
673int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
674 int32_t scanCode) {
675 AutoMutex _l(mLock);
676
677 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
678}
679
680int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
681 AutoMutex _l(mLock);
682
683 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
684}
685
686int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
687 GetStateFunc getStateFunc) {
688 int32_t result = AKEY_STATE_UNKNOWN;
689 if (deviceId >= 0) {
690 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
691 if (deviceIndex >= 0) {
692 InputDevice* device = mDevices.valueAt(deviceIndex);
693 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
694 result = (device->*getStateFunc)(sourceMask, code);
695 }
696 }
697 } else {
698 size_t numDevices = mDevices.size();
699 for (size_t i = 0; i < numDevices; i++) {
700 InputDevice* device = mDevices.valueAt(i);
701 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
702 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
703 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
704 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
705 if (currentResult >= AKEY_STATE_DOWN) {
706 return currentResult;
707 } else if (currentResult == AKEY_STATE_UP) {
708 result = currentResult;
709 }
710 }
711 }
712 }
713 return result;
714}
715
Andrii Kulian763a3a42016-03-08 10:46:16 -0800716void InputReader::toggleCapsLockState(int32_t deviceId) {
717 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
718 if (deviceIndex < 0) {
719 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
720 return;
721 }
722
723 InputDevice* device = mDevices.valueAt(deviceIndex);
724 if (device->isIgnored()) {
725 return;
726 }
727
728 device->updateMetaState(AKEYCODE_CAPS_LOCK);
729}
730
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
732 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
733 AutoMutex _l(mLock);
734
735 memset(outFlags, 0, numCodes);
736 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
737}
738
739bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
740 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
741 bool result = false;
742 if (deviceId >= 0) {
743 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
744 if (deviceIndex >= 0) {
745 InputDevice* device = mDevices.valueAt(deviceIndex);
746 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
747 result = device->markSupportedKeyCodes(sourceMask,
748 numCodes, keyCodes, outFlags);
749 }
750 }
751 } else {
752 size_t numDevices = mDevices.size();
753 for (size_t i = 0; i < numDevices; i++) {
754 InputDevice* device = mDevices.valueAt(i);
755 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
756 result |= device->markSupportedKeyCodes(sourceMask,
757 numCodes, keyCodes, outFlags);
758 }
759 }
760 }
761 return result;
762}
763
764void InputReader::requestRefreshConfiguration(uint32_t changes) {
765 AutoMutex _l(mLock);
766
767 if (changes) {
768 bool needWake = !mConfigurationChangesToRefresh;
769 mConfigurationChangesToRefresh |= changes;
770
771 if (needWake) {
772 mEventHub->wake();
773 }
774 }
775}
776
777void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
778 ssize_t repeat, int32_t token) {
779 AutoMutex _l(mLock);
780
781 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
782 if (deviceIndex >= 0) {
783 InputDevice* device = mDevices.valueAt(deviceIndex);
784 device->vibrate(pattern, patternSize, repeat, token);
785 }
786}
787
788void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
789 AutoMutex _l(mLock);
790
791 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
792 if (deviceIndex >= 0) {
793 InputDevice* device = mDevices.valueAt(deviceIndex);
794 device->cancelVibrate(token);
795 }
796}
797
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700798bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
799 AutoMutex _l(mLock);
800
801 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
802 if (deviceIndex >= 0) {
803 InputDevice* device = mDevices.valueAt(deviceIndex);
804 return device->isEnabled();
805 }
806 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
807 return false;
808}
809
Arthur Hungc23540e2018-11-29 20:42:11 +0800810bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
811 AutoMutex _l(mLock);
812
813 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
814 if (deviceIndex < 0) {
815 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
816 return false;
817 }
818
819 InputDevice* device = mDevices.valueAt(deviceIndex);
820 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
821 // No associated display. By default, can dispatch to all displays.
822 if (!associatedDisplayId) {
823 return true;
824 }
825
826 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
827 ALOGW("Device has associated, but no associated display id.");
828 return true;
829 }
830
831 return *associatedDisplayId == displayId;
832}
833
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800834void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 AutoMutex _l(mLock);
836
837 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800838 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800840 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841
842 for (size_t i = 0; i < mDevices.size(); i++) {
843 mDevices.valueAt(i)->dump(dump);
844 }
845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += INDENT "Configuration:\n";
847 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
849 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100852 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800854 dump += "]\n";
855 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 mConfig.virtualKeyQuietTime * 0.000001f);
857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
860 mConfig.pointerVelocityControlParameters.scale,
861 mConfig.pointerVelocityControlParameters.lowThreshold,
862 mConfig.pointerVelocityControlParameters.highThreshold,
863 mConfig.pointerVelocityControlParameters.acceleration);
864
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
867 mConfig.wheelVelocityControlParameters.scale,
868 mConfig.wheelVelocityControlParameters.lowThreshold,
869 mConfig.wheelVelocityControlParameters.highThreshold,
870 mConfig.wheelVelocityControlParameters.acceleration);
871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += StringPrintf(INDENT2 "PointerGesture:\n");
873 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800875 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800877 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800881 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700897
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800898 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700899 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900}
901
902void InputReader::monitor() {
903 // Acquire and release the lock to ensure that the reader has not deadlocked.
904 mLock.lock();
905 mEventHub->wake();
906 mReaderIsAliveCondition.wait(mLock);
907 mLock.unlock();
908
909 // Check the EventHub
910 mEventHub->monitor();
911}
912
913
914// --- InputReader::ContextImpl ---
915
916InputReader::ContextImpl::ContextImpl(InputReader* reader) :
917 mReader(reader) {
918}
919
920void InputReader::ContextImpl::updateGlobalMetaState() {
921 // lock is already held by the input loop
922 mReader->updateGlobalMetaStateLocked();
923}
924
925int32_t InputReader::ContextImpl::getGlobalMetaState() {
926 // lock is already held by the input loop
927 return mReader->getGlobalMetaStateLocked();
928}
929
930void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
931 // lock is already held by the input loop
932 mReader->disableVirtualKeysUntilLocked(time);
933}
934
935bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
936 InputDevice* device, int32_t keyCode, int32_t scanCode) {
937 // lock is already held by the input loop
938 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
939}
940
941void InputReader::ContextImpl::fadePointer() {
942 // lock is already held by the input loop
943 mReader->fadePointerLocked();
944}
945
946void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
947 // lock is already held by the input loop
948 mReader->requestTimeoutAtTimeLocked(when);
949}
950
951int32_t InputReader::ContextImpl::bumpGeneration() {
952 // lock is already held by the input loop
953 return mReader->bumpGenerationLocked();
954}
955
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800956void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700957 // lock is already held by whatever called refreshConfigurationLocked
958 mReader->getExternalStylusDevicesLocked(outDevices);
959}
960
961void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
962 mReader->dispatchExternalStylusState(state);
963}
964
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
966 return mReader->mPolicy.get();
967}
968
969InputListenerInterface* InputReader::ContextImpl::getListener() {
970 return mReader->mQueuedListener.get();
971}
972
973EventHubInterface* InputReader::ContextImpl::getEventHub() {
974 return mReader->mEventHub.get();
975}
976
Prabir Pradhan42611e02018-11-27 14:04:02 -0800977uint32_t InputReader::ContextImpl::getNextSequenceNum() {
978 return (mReader->mNextSequenceNum)++;
979}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981// --- InputDevice ---
982
983InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
984 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
985 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
986 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700987 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988}
989
990InputDevice::~InputDevice() {
991 size_t numMappers = mMappers.size();
992 for (size_t i = 0; i < numMappers; i++) {
993 delete mMappers[i];
994 }
995 mMappers.clear();
996}
997
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700998bool InputDevice::isEnabled() {
999 return getEventHub()->isDeviceEnabled(mId);
1000}
1001
1002void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1003 if (isEnabled() == enabled) {
1004 return;
1005 }
1006
1007 if (enabled) {
1008 getEventHub()->enableDevice(mId);
1009 reset(when);
1010 } else {
1011 reset(when);
1012 getEventHub()->disableDevice(mId);
1013 }
1014 // Must change generation to flag this device as changed
1015 bumpGeneration();
1016}
1017
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001018void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001020 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001022 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001023 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001024 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1025 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001026 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1027 if (mAssociatedDisplayPort) {
1028 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1029 } else {
1030 dump += "<none>\n";
1031 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001032 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1033 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1034 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001036 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1037 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001038 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001040 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 const char* label = getAxisLabel(range.axis);
1042 char name[32];
1043 if (label) {
1044 strncpy(name, label, sizeof(name));
1045 name[sizeof(name) - 1] = '\0';
1046 } else {
1047 snprintf(name, sizeof(name), "%d", range.axis);
1048 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001049 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1051 name, range.source, range.min, range.max, range.flat, range.fuzz,
1052 range.resolution);
1053 }
1054 }
1055
1056 size_t numMappers = mMappers.size();
1057 for (size_t i = 0; i < numMappers; i++) {
1058 InputMapper* mapper = mMappers[i];
1059 mapper->dump(dump);
1060 }
1061}
1062
1063void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001064 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065}
1066
1067void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1068 mSources = 0;
1069
1070 if (!isIgnored()) {
1071 if (!changes) { // first time only
1072 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1073 }
1074
1075 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1076 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1077 sp<KeyCharacterMap> keyboardLayout =
1078 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1079 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1080 bumpGeneration();
1081 }
1082 }
1083 }
1084
1085 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1086 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001087 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 if (mAlias != alias) {
1089 mAlias = alias;
1090 bumpGeneration();
1091 }
1092 }
1093 }
1094
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001095 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1096 ssize_t index = config->disabledDevices.indexOf(mId);
1097 bool enabled = index < 0;
1098 setEnabled(enabled, when);
1099 }
1100
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001101 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1102 // In most situations, no port will be specified.
1103 mAssociatedDisplayPort = std::nullopt;
1104 // Find the display port that corresponds to the current input port.
1105 const std::string& inputPort = mIdentifier.location;
1106 if (!inputPort.empty()) {
1107 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1108 const auto& displayPort = ports.find(inputPort);
1109 if (displayPort != ports.end()) {
1110 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1111 }
1112 }
1113 }
1114
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001115 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 mapper->configure(when, config, changes);
1117 mSources |= mapper->getSources();
1118 }
1119 }
1120}
1121
1122void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001123 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 mapper->reset(when);
1125 }
1126
1127 mContext->updateGlobalMetaState();
1128
1129 notifyReset(when);
1130}
1131
1132void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1133 // Process all of the events in order for each mapper.
1134 // We cannot simply ask each mapper to process them in bulk because mappers may
1135 // have side-effects that must be interleaved. For example, joystick movement events and
1136 // gamepad button presses are handled by different mappers but they should be dispatched
1137 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001138 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001140 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1142 rawEvent->when);
1143#endif
1144
1145 if (mDropUntilNextSync) {
1146 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1147 mDropUntilNextSync = false;
1148#if DEBUG_RAW_EVENTS
1149 ALOGD("Recovered from input event buffer overrun.");
1150#endif
1151 } else {
1152#if DEBUG_RAW_EVENTS
1153 ALOGD("Dropped input event while waiting for next input sync.");
1154#endif
1155 }
1156 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001157 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 mDropUntilNextSync = true;
1159 reset(rawEvent->when);
1160 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001161 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 mapper->process(rawEvent);
1163 }
1164 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001165 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167}
1168
1169void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001170 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 mapper->timeoutExpired(when);
1172 }
1173}
1174
Michael Wright842500e2015-03-13 17:32:02 -07001175void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001176 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001177 mapper->updateExternalStylusState(state);
1178 }
1179}
1180
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1182 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001183 mIsExternal, mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001184 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 mapper->populateDeviceInfo(outDeviceInfo);
1186 }
1187}
1188
1189int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1190 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1191}
1192
1193int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1194 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1195}
1196
1197int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1198 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1199}
1200
1201int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1202 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001203 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1205 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1206 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1207 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1208 if (currentResult >= AKEY_STATE_DOWN) {
1209 return currentResult;
1210 } else if (currentResult == AKEY_STATE_UP) {
1211 result = currentResult;
1212 }
1213 }
1214 }
1215 return result;
1216}
1217
1218bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1219 const int32_t* keyCodes, uint8_t* outFlags) {
1220 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001221 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1223 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1224 }
1225 }
1226 return result;
1227}
1228
1229void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1230 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001231 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 mapper->vibrate(pattern, patternSize, repeat, token);
1233 }
1234}
1235
1236void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001237 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 mapper->cancelVibrate(token);
1239 }
1240}
1241
Jeff Brownc9aa6282015-02-11 19:03:28 -08001242void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001243 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001244 mapper->cancelTouch(when);
1245 }
1246}
1247
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248int32_t InputDevice::getMetaState() {
1249 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001250 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 result |= mapper->getMetaState();
1252 }
1253 return result;
1254}
1255
Andrii Kulian763a3a42016-03-08 10:46:16 -08001256void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001257 for (InputMapper* mapper : mMappers) {
1258 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001259 }
1260}
1261
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001263 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 mapper->fadePointer();
1265 }
1266}
1267
1268void InputDevice::bumpGeneration() {
1269 mGeneration = mContext->bumpGeneration();
1270}
1271
1272void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001273 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 mContext->getListener()->notifyDeviceReset(&args);
1275}
1276
Arthur Hungc23540e2018-11-29 20:42:11 +08001277std::optional<int32_t> InputDevice::getAssociatedDisplay() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001278 for (InputMapper* mapper : mMappers) {
Arthur Hungc23540e2018-11-29 20:42:11 +08001279 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1280 if (associatedDisplayId) {
1281 return associatedDisplayId;
1282 }
1283 }
1284
1285 return std::nullopt;
1286}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
1288// --- CursorButtonAccumulator ---
1289
1290CursorButtonAccumulator::CursorButtonAccumulator() {
1291 clearButtons();
1292}
1293
1294void CursorButtonAccumulator::reset(InputDevice* device) {
1295 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1296 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1297 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1298 mBtnBack = device->isKeyPressed(BTN_BACK);
1299 mBtnSide = device->isKeyPressed(BTN_SIDE);
1300 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1301 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1302 mBtnTask = device->isKeyPressed(BTN_TASK);
1303}
1304
1305void CursorButtonAccumulator::clearButtons() {
1306 mBtnLeft = 0;
1307 mBtnRight = 0;
1308 mBtnMiddle = 0;
1309 mBtnBack = 0;
1310 mBtnSide = 0;
1311 mBtnForward = 0;
1312 mBtnExtra = 0;
1313 mBtnTask = 0;
1314}
1315
1316void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1317 if (rawEvent->type == EV_KEY) {
1318 switch (rawEvent->code) {
1319 case BTN_LEFT:
1320 mBtnLeft = rawEvent->value;
1321 break;
1322 case BTN_RIGHT:
1323 mBtnRight = rawEvent->value;
1324 break;
1325 case BTN_MIDDLE:
1326 mBtnMiddle = rawEvent->value;
1327 break;
1328 case BTN_BACK:
1329 mBtnBack = rawEvent->value;
1330 break;
1331 case BTN_SIDE:
1332 mBtnSide = rawEvent->value;
1333 break;
1334 case BTN_FORWARD:
1335 mBtnForward = rawEvent->value;
1336 break;
1337 case BTN_EXTRA:
1338 mBtnExtra = rawEvent->value;
1339 break;
1340 case BTN_TASK:
1341 mBtnTask = rawEvent->value;
1342 break;
1343 }
1344 }
1345}
1346
1347uint32_t CursorButtonAccumulator::getButtonState() const {
1348 uint32_t result = 0;
1349 if (mBtnLeft) {
1350 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1351 }
1352 if (mBtnRight) {
1353 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1354 }
1355 if (mBtnMiddle) {
1356 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1357 }
1358 if (mBtnBack || mBtnSide) {
1359 result |= AMOTION_EVENT_BUTTON_BACK;
1360 }
1361 if (mBtnForward || mBtnExtra) {
1362 result |= AMOTION_EVENT_BUTTON_FORWARD;
1363 }
1364 return result;
1365}
1366
1367
1368// --- CursorMotionAccumulator ---
1369
1370CursorMotionAccumulator::CursorMotionAccumulator() {
1371 clearRelativeAxes();
1372}
1373
1374void CursorMotionAccumulator::reset(InputDevice* device) {
1375 clearRelativeAxes();
1376}
1377
1378void CursorMotionAccumulator::clearRelativeAxes() {
1379 mRelX = 0;
1380 mRelY = 0;
1381}
1382
1383void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1384 if (rawEvent->type == EV_REL) {
1385 switch (rawEvent->code) {
1386 case REL_X:
1387 mRelX = rawEvent->value;
1388 break;
1389 case REL_Y:
1390 mRelY = rawEvent->value;
1391 break;
1392 }
1393 }
1394}
1395
1396void CursorMotionAccumulator::finishSync() {
1397 clearRelativeAxes();
1398}
1399
1400
1401// --- CursorScrollAccumulator ---
1402
1403CursorScrollAccumulator::CursorScrollAccumulator() :
1404 mHaveRelWheel(false), mHaveRelHWheel(false) {
1405 clearRelativeAxes();
1406}
1407
1408void CursorScrollAccumulator::configure(InputDevice* device) {
1409 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1410 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1411}
1412
1413void CursorScrollAccumulator::reset(InputDevice* device) {
1414 clearRelativeAxes();
1415}
1416
1417void CursorScrollAccumulator::clearRelativeAxes() {
1418 mRelWheel = 0;
1419 mRelHWheel = 0;
1420}
1421
1422void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1423 if (rawEvent->type == EV_REL) {
1424 switch (rawEvent->code) {
1425 case REL_WHEEL:
1426 mRelWheel = rawEvent->value;
1427 break;
1428 case REL_HWHEEL:
1429 mRelHWheel = rawEvent->value;
1430 break;
1431 }
1432 }
1433}
1434
1435void CursorScrollAccumulator::finishSync() {
1436 clearRelativeAxes();
1437}
1438
1439
1440// --- TouchButtonAccumulator ---
1441
1442TouchButtonAccumulator::TouchButtonAccumulator() :
1443 mHaveBtnTouch(false), mHaveStylus(false) {
1444 clearButtons();
1445}
1446
1447void TouchButtonAccumulator::configure(InputDevice* device) {
1448 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1449 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1450 || device->hasKey(BTN_TOOL_RUBBER)
1451 || device->hasKey(BTN_TOOL_BRUSH)
1452 || device->hasKey(BTN_TOOL_PENCIL)
1453 || device->hasKey(BTN_TOOL_AIRBRUSH);
1454}
1455
1456void TouchButtonAccumulator::reset(InputDevice* device) {
1457 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1458 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001459 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1460 mBtnStylus2 =
1461 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1463 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1464 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1465 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1466 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1467 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1468 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1469 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1470 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1471 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1472 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1473}
1474
1475void TouchButtonAccumulator::clearButtons() {
1476 mBtnTouch = 0;
1477 mBtnStylus = 0;
1478 mBtnStylus2 = 0;
1479 mBtnToolFinger = 0;
1480 mBtnToolPen = 0;
1481 mBtnToolRubber = 0;
1482 mBtnToolBrush = 0;
1483 mBtnToolPencil = 0;
1484 mBtnToolAirbrush = 0;
1485 mBtnToolMouse = 0;
1486 mBtnToolLens = 0;
1487 mBtnToolDoubleTap = 0;
1488 mBtnToolTripleTap = 0;
1489 mBtnToolQuadTap = 0;
1490}
1491
1492void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1493 if (rawEvent->type == EV_KEY) {
1494 switch (rawEvent->code) {
1495 case BTN_TOUCH:
1496 mBtnTouch = rawEvent->value;
1497 break;
1498 case BTN_STYLUS:
1499 mBtnStylus = rawEvent->value;
1500 break;
1501 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001502 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 mBtnStylus2 = rawEvent->value;
1504 break;
1505 case BTN_TOOL_FINGER:
1506 mBtnToolFinger = rawEvent->value;
1507 break;
1508 case BTN_TOOL_PEN:
1509 mBtnToolPen = rawEvent->value;
1510 break;
1511 case BTN_TOOL_RUBBER:
1512 mBtnToolRubber = rawEvent->value;
1513 break;
1514 case BTN_TOOL_BRUSH:
1515 mBtnToolBrush = rawEvent->value;
1516 break;
1517 case BTN_TOOL_PENCIL:
1518 mBtnToolPencil = rawEvent->value;
1519 break;
1520 case BTN_TOOL_AIRBRUSH:
1521 mBtnToolAirbrush = rawEvent->value;
1522 break;
1523 case BTN_TOOL_MOUSE:
1524 mBtnToolMouse = rawEvent->value;
1525 break;
1526 case BTN_TOOL_LENS:
1527 mBtnToolLens = rawEvent->value;
1528 break;
1529 case BTN_TOOL_DOUBLETAP:
1530 mBtnToolDoubleTap = rawEvent->value;
1531 break;
1532 case BTN_TOOL_TRIPLETAP:
1533 mBtnToolTripleTap = rawEvent->value;
1534 break;
1535 case BTN_TOOL_QUADTAP:
1536 mBtnToolQuadTap = rawEvent->value;
1537 break;
1538 }
1539 }
1540}
1541
1542uint32_t TouchButtonAccumulator::getButtonState() const {
1543 uint32_t result = 0;
1544 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001545 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001548 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550 return result;
1551}
1552
1553int32_t TouchButtonAccumulator::getToolType() const {
1554 if (mBtnToolMouse || mBtnToolLens) {
1555 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1556 }
1557 if (mBtnToolRubber) {
1558 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1559 }
1560 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1561 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1562 }
1563 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1564 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1565 }
1566 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1567}
1568
1569bool TouchButtonAccumulator::isToolActive() const {
1570 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1571 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1572 || mBtnToolMouse || mBtnToolLens
1573 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1574}
1575
1576bool TouchButtonAccumulator::isHovering() const {
1577 return mHaveBtnTouch && !mBtnTouch;
1578}
1579
1580bool TouchButtonAccumulator::hasStylus() const {
1581 return mHaveStylus;
1582}
1583
1584
1585// --- RawPointerAxes ---
1586
1587RawPointerAxes::RawPointerAxes() {
1588 clear();
1589}
1590
1591void RawPointerAxes::clear() {
1592 x.clear();
1593 y.clear();
1594 pressure.clear();
1595 touchMajor.clear();
1596 touchMinor.clear();
1597 toolMajor.clear();
1598 toolMinor.clear();
1599 orientation.clear();
1600 distance.clear();
1601 tiltX.clear();
1602 tiltY.clear();
1603 trackingId.clear();
1604 slot.clear();
1605}
1606
1607
1608// --- RawPointerData ---
1609
1610RawPointerData::RawPointerData() {
1611 clear();
1612}
1613
1614void RawPointerData::clear() {
1615 pointerCount = 0;
1616 clearIdBits();
1617}
1618
1619void RawPointerData::copyFrom(const RawPointerData& other) {
1620 pointerCount = other.pointerCount;
1621 hoveringIdBits = other.hoveringIdBits;
1622 touchingIdBits = other.touchingIdBits;
1623
1624 for (uint32_t i = 0; i < pointerCount; i++) {
1625 pointers[i] = other.pointers[i];
1626
1627 int id = pointers[i].id;
1628 idToIndex[id] = other.idToIndex[id];
1629 }
1630}
1631
1632void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1633 float x = 0, y = 0;
1634 uint32_t count = touchingIdBits.count();
1635 if (count) {
1636 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1637 uint32_t id = idBits.clearFirstMarkedBit();
1638 const Pointer& pointer = pointerForId(id);
1639 x += pointer.x;
1640 y += pointer.y;
1641 }
1642 x /= count;
1643 y /= count;
1644 }
1645 *outX = x;
1646 *outY = y;
1647}
1648
1649
1650// --- CookedPointerData ---
1651
1652CookedPointerData::CookedPointerData() {
1653 clear();
1654}
1655
1656void CookedPointerData::clear() {
1657 pointerCount = 0;
1658 hoveringIdBits.clear();
1659 touchingIdBits.clear();
1660}
1661
1662void CookedPointerData::copyFrom(const CookedPointerData& other) {
1663 pointerCount = other.pointerCount;
1664 hoveringIdBits = other.hoveringIdBits;
1665 touchingIdBits = other.touchingIdBits;
1666
1667 for (uint32_t i = 0; i < pointerCount; i++) {
1668 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1669 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1670
1671 int id = pointerProperties[i].id;
1672 idToIndex[id] = other.idToIndex[id];
1673 }
1674}
1675
1676
1677// --- SingleTouchMotionAccumulator ---
1678
1679SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1680 clearAbsoluteAxes();
1681}
1682
1683void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1684 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1685 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1686 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1687 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1688 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1689 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1690 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1691}
1692
1693void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1694 mAbsX = 0;
1695 mAbsY = 0;
1696 mAbsPressure = 0;
1697 mAbsToolWidth = 0;
1698 mAbsDistance = 0;
1699 mAbsTiltX = 0;
1700 mAbsTiltY = 0;
1701}
1702
1703void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1704 if (rawEvent->type == EV_ABS) {
1705 switch (rawEvent->code) {
1706 case ABS_X:
1707 mAbsX = rawEvent->value;
1708 break;
1709 case ABS_Y:
1710 mAbsY = rawEvent->value;
1711 break;
1712 case ABS_PRESSURE:
1713 mAbsPressure = rawEvent->value;
1714 break;
1715 case ABS_TOOL_WIDTH:
1716 mAbsToolWidth = rawEvent->value;
1717 break;
1718 case ABS_DISTANCE:
1719 mAbsDistance = rawEvent->value;
1720 break;
1721 case ABS_TILT_X:
1722 mAbsTiltX = rawEvent->value;
1723 break;
1724 case ABS_TILT_Y:
1725 mAbsTiltY = rawEvent->value;
1726 break;
1727 }
1728 }
1729}
1730
1731
1732// --- MultiTouchMotionAccumulator ---
1733
1734MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001735 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001736 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001737}
1738
1739MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1740 delete[] mSlots;
1741}
1742
1743void MultiTouchMotionAccumulator::configure(InputDevice* device,
1744 size_t slotCount, bool usingSlotsProtocol) {
1745 mSlotCount = slotCount;
1746 mUsingSlotsProtocol = usingSlotsProtocol;
1747 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1748
1749 delete[] mSlots;
1750 mSlots = new Slot[slotCount];
1751}
1752
1753void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1754 // Unfortunately there is no way to read the initial contents of the slots.
1755 // So when we reset the accumulator, we must assume they are all zeroes.
1756 if (mUsingSlotsProtocol) {
1757 // Query the driver for the current slot index and use it as the initial slot
1758 // before we start reading events from the device. It is possible that the
1759 // current slot index will not be the same as it was when the first event was
1760 // written into the evdev buffer, which means the input mapper could start
1761 // out of sync with the initial state of the events in the evdev buffer.
1762 // In the extremely unlikely case that this happens, the data from
1763 // two slots will be confused until the next ABS_MT_SLOT event is received.
1764 // This can cause the touch point to "jump", but at least there will be
1765 // no stuck touches.
1766 int32_t initialSlot;
1767 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1768 ABS_MT_SLOT, &initialSlot);
1769 if (status) {
1770 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1771 initialSlot = -1;
1772 }
1773 clearSlots(initialSlot);
1774 } else {
1775 clearSlots(-1);
1776 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001777 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001778}
1779
1780void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1781 if (mSlots) {
1782 for (size_t i = 0; i < mSlotCount; i++) {
1783 mSlots[i].clear();
1784 }
1785 }
1786 mCurrentSlot = initialSlot;
1787}
1788
1789void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1790 if (rawEvent->type == EV_ABS) {
1791 bool newSlot = false;
1792 if (mUsingSlotsProtocol) {
1793 if (rawEvent->code == ABS_MT_SLOT) {
1794 mCurrentSlot = rawEvent->value;
1795 newSlot = true;
1796 }
1797 } else if (mCurrentSlot < 0) {
1798 mCurrentSlot = 0;
1799 }
1800
1801 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1802#if DEBUG_POINTERS
1803 if (newSlot) {
1804 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001805 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001806 mCurrentSlot, mSlotCount - 1);
1807 }
1808#endif
1809 } else {
1810 Slot* slot = &mSlots[mCurrentSlot];
1811
1812 switch (rawEvent->code) {
1813 case ABS_MT_POSITION_X:
1814 slot->mInUse = true;
1815 slot->mAbsMTPositionX = rawEvent->value;
1816 break;
1817 case ABS_MT_POSITION_Y:
1818 slot->mInUse = true;
1819 slot->mAbsMTPositionY = rawEvent->value;
1820 break;
1821 case ABS_MT_TOUCH_MAJOR:
1822 slot->mInUse = true;
1823 slot->mAbsMTTouchMajor = rawEvent->value;
1824 break;
1825 case ABS_MT_TOUCH_MINOR:
1826 slot->mInUse = true;
1827 slot->mAbsMTTouchMinor = rawEvent->value;
1828 slot->mHaveAbsMTTouchMinor = true;
1829 break;
1830 case ABS_MT_WIDTH_MAJOR:
1831 slot->mInUse = true;
1832 slot->mAbsMTWidthMajor = rawEvent->value;
1833 break;
1834 case ABS_MT_WIDTH_MINOR:
1835 slot->mInUse = true;
1836 slot->mAbsMTWidthMinor = rawEvent->value;
1837 slot->mHaveAbsMTWidthMinor = true;
1838 break;
1839 case ABS_MT_ORIENTATION:
1840 slot->mInUse = true;
1841 slot->mAbsMTOrientation = rawEvent->value;
1842 break;
1843 case ABS_MT_TRACKING_ID:
1844 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1845 // The slot is no longer in use but it retains its previous contents,
1846 // which may be reused for subsequent touches.
1847 slot->mInUse = false;
1848 } else {
1849 slot->mInUse = true;
1850 slot->mAbsMTTrackingId = rawEvent->value;
1851 }
1852 break;
1853 case ABS_MT_PRESSURE:
1854 slot->mInUse = true;
1855 slot->mAbsMTPressure = rawEvent->value;
1856 break;
1857 case ABS_MT_DISTANCE:
1858 slot->mInUse = true;
1859 slot->mAbsMTDistance = rawEvent->value;
1860 break;
1861 case ABS_MT_TOOL_TYPE:
1862 slot->mInUse = true;
1863 slot->mAbsMTToolType = rawEvent->value;
1864 slot->mHaveAbsMTToolType = true;
1865 break;
1866 }
1867 }
1868 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1869 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1870 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001871 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1872 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001873 }
1874}
1875
1876void MultiTouchMotionAccumulator::finishSync() {
1877 if (!mUsingSlotsProtocol) {
1878 clearSlots(-1);
1879 }
1880}
1881
1882bool MultiTouchMotionAccumulator::hasStylus() const {
1883 return mHaveStylus;
1884}
1885
1886
1887// --- MultiTouchMotionAccumulator::Slot ---
1888
1889MultiTouchMotionAccumulator::Slot::Slot() {
1890 clear();
1891}
1892
1893void MultiTouchMotionAccumulator::Slot::clear() {
1894 mInUse = false;
1895 mHaveAbsMTTouchMinor = false;
1896 mHaveAbsMTWidthMinor = false;
1897 mHaveAbsMTToolType = false;
1898 mAbsMTPositionX = 0;
1899 mAbsMTPositionY = 0;
1900 mAbsMTTouchMajor = 0;
1901 mAbsMTTouchMinor = 0;
1902 mAbsMTWidthMajor = 0;
1903 mAbsMTWidthMinor = 0;
1904 mAbsMTOrientation = 0;
1905 mAbsMTTrackingId = -1;
1906 mAbsMTPressure = 0;
1907 mAbsMTDistance = 0;
1908 mAbsMTToolType = 0;
1909}
1910
1911int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1912 if (mHaveAbsMTToolType) {
1913 switch (mAbsMTToolType) {
1914 case MT_TOOL_FINGER:
1915 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1916 case MT_TOOL_PEN:
1917 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1918 }
1919 }
1920 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1921}
1922
1923
1924// --- InputMapper ---
1925
1926InputMapper::InputMapper(InputDevice* device) :
1927 mDevice(device), mContext(device->getContext()) {
1928}
1929
1930InputMapper::~InputMapper() {
1931}
1932
1933void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1934 info->addSource(getSources());
1935}
1936
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001937void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938}
1939
1940void InputMapper::configure(nsecs_t when,
1941 const InputReaderConfiguration* config, uint32_t changes) {
1942}
1943
1944void InputMapper::reset(nsecs_t when) {
1945}
1946
1947void InputMapper::timeoutExpired(nsecs_t when) {
1948}
1949
1950int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1951 return AKEY_STATE_UNKNOWN;
1952}
1953
1954int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1955 return AKEY_STATE_UNKNOWN;
1956}
1957
1958int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1959 return AKEY_STATE_UNKNOWN;
1960}
1961
1962bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1963 const int32_t* keyCodes, uint8_t* outFlags) {
1964 return false;
1965}
1966
1967void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1968 int32_t token) {
1969}
1970
1971void InputMapper::cancelVibrate(int32_t token) {
1972}
1973
Jeff Brownc9aa6282015-02-11 19:03:28 -08001974void InputMapper::cancelTouch(nsecs_t when) {
1975}
1976
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977int32_t InputMapper::getMetaState() {
1978 return 0;
1979}
1980
Andrii Kulian763a3a42016-03-08 10:46:16 -08001981void InputMapper::updateMetaState(int32_t keyCode) {
1982}
1983
Michael Wright842500e2015-03-13 17:32:02 -07001984void InputMapper::updateExternalStylusState(const StylusState& state) {
1985
1986}
1987
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988void InputMapper::fadePointer() {
1989}
1990
1991status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1992 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1993}
1994
1995void InputMapper::bumpGeneration() {
1996 mDevice->bumpGeneration();
1997}
1998
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001999void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 const RawAbsoluteAxisInfo& axis, const char* name) {
2001 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002002 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2004 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002005 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007}
2008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002009void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2010 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2011 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2012 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2013 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002014}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015
2016// --- SwitchInputMapper ---
2017
2018SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002019 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020}
2021
2022SwitchInputMapper::~SwitchInputMapper() {
2023}
2024
2025uint32_t SwitchInputMapper::getSources() {
2026 return AINPUT_SOURCE_SWITCH;
2027}
2028
2029void SwitchInputMapper::process(const RawEvent* rawEvent) {
2030 switch (rawEvent->type) {
2031 case EV_SW:
2032 processSwitch(rawEvent->code, rawEvent->value);
2033 break;
2034
2035 case EV_SYN:
2036 if (rawEvent->code == SYN_REPORT) {
2037 sync(rawEvent->when);
2038 }
2039 }
2040}
2041
2042void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2043 if (switchCode >= 0 && switchCode < 32) {
2044 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002045 mSwitchValues |= 1 << switchCode;
2046 } else {
2047 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
2049 mUpdatedSwitchMask |= 1 << switchCode;
2050 }
2051}
2052
2053void SwitchInputMapper::sync(nsecs_t when) {
2054 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002055 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002056 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2057 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 getListener()->notifySwitch(&args);
2059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 mUpdatedSwitchMask = 0;
2061 }
2062}
2063
2064int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2065 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2066}
2067
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002068void SwitchInputMapper::dump(std::string& dump) {
2069 dump += INDENT2 "Switch Input Mapper:\n";
2070 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002071}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072
2073// --- VibratorInputMapper ---
2074
2075VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2076 InputMapper(device), mVibrating(false) {
2077}
2078
2079VibratorInputMapper::~VibratorInputMapper() {
2080}
2081
2082uint32_t VibratorInputMapper::getSources() {
2083 return 0;
2084}
2085
2086void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2087 InputMapper::populateDeviceInfo(info);
2088
2089 info->setVibrator(true);
2090}
2091
2092void VibratorInputMapper::process(const RawEvent* rawEvent) {
2093 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2094}
2095
2096void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2097 int32_t token) {
2098#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002099 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 for (size_t i = 0; i < patternSize; i++) {
2101 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002102 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002104 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002106 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002107 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108#endif
2109
2110 mVibrating = true;
2111 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2112 mPatternSize = patternSize;
2113 mRepeat = repeat;
2114 mToken = token;
2115 mIndex = -1;
2116
2117 nextStep();
2118}
2119
2120void VibratorInputMapper::cancelVibrate(int32_t token) {
2121#if DEBUG_VIBRATOR
2122 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2123#endif
2124
2125 if (mVibrating && mToken == token) {
2126 stopVibrating();
2127 }
2128}
2129
2130void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2131 if (mVibrating) {
2132 if (when >= mNextStepTime) {
2133 nextStep();
2134 } else {
2135 getContext()->requestTimeoutAtTime(mNextStepTime);
2136 }
2137 }
2138}
2139
2140void VibratorInputMapper::nextStep() {
2141 mIndex += 1;
2142 if (size_t(mIndex) >= mPatternSize) {
2143 if (mRepeat < 0) {
2144 // We are done.
2145 stopVibrating();
2146 return;
2147 }
2148 mIndex = mRepeat;
2149 }
2150
2151 bool vibratorOn = mIndex & 1;
2152 nsecs_t duration = mPattern[mIndex];
2153 if (vibratorOn) {
2154#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002155 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156#endif
2157 getEventHub()->vibrate(getDeviceId(), duration);
2158 } else {
2159#if DEBUG_VIBRATOR
2160 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2161#endif
2162 getEventHub()->cancelVibrate(getDeviceId());
2163 }
2164 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2165 mNextStepTime = now + duration;
2166 getContext()->requestTimeoutAtTime(mNextStepTime);
2167#if DEBUG_VIBRATOR
2168 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2169#endif
2170}
2171
2172void VibratorInputMapper::stopVibrating() {
2173 mVibrating = false;
2174#if DEBUG_VIBRATOR
2175 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2176#endif
2177 getEventHub()->cancelVibrate(getDeviceId());
2178}
2179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002180void VibratorInputMapper::dump(std::string& dump) {
2181 dump += INDENT2 "Vibrator Input Mapper:\n";
2182 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183}
2184
2185
2186// --- KeyboardInputMapper ---
2187
2188KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2189 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002190 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191}
2192
2193KeyboardInputMapper::~KeyboardInputMapper() {
2194}
2195
2196uint32_t KeyboardInputMapper::getSources() {
2197 return mSource;
2198}
2199
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002200int32_t KeyboardInputMapper::getOrientation() {
2201 if (mViewport) {
2202 return mViewport->orientation;
2203 }
2204 return DISPLAY_ORIENTATION_0;
2205}
2206
2207int32_t KeyboardInputMapper::getDisplayId() {
2208 if (mViewport) {
2209 return mViewport->displayId;
2210 }
2211 return ADISPLAY_ID_NONE;
2212}
2213
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2215 InputMapper::populateDeviceInfo(info);
2216
2217 info->setKeyboardType(mKeyboardType);
2218 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2219}
2220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002221void KeyboardInputMapper::dump(std::string& dump) {
2222 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002224 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002225 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002226 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2227 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2228 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229}
2230
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231void KeyboardInputMapper::configure(nsecs_t when,
2232 const InputReaderConfiguration* config, uint32_t changes) {
2233 InputMapper::configure(when, config, changes);
2234
2235 if (!changes) { // first time only
2236 // Configure basic parameters.
2237 configureParameters();
2238 }
2239
2240 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002241 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002242 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 }
2244 }
2245}
2246
Ivan Podogovb9afef32017-02-13 15:34:32 +00002247static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2248 int32_t mapped = 0;
2249 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2250 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2251 if (stemKeyRotationMap[i][0] == keyCode) {
2252 stemKeyRotationMap[i][1] = mapped;
2253 return;
2254 }
2255 }
2256 }
2257}
2258
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259void KeyboardInputMapper::configureParameters() {
2260 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002261 const PropertyMap& config = getDevice()->getConfiguration();
2262 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 mParameters.orientationAware);
2264
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002266 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2267 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2268 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2269 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002271
2272 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002273 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002274 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275}
2276
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002277void KeyboardInputMapper::dumpParameters(std::string& dump) {
2278 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002279 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002281 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002282 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283}
2284
2285void KeyboardInputMapper::reset(nsecs_t when) {
2286 mMetaState = AMETA_NONE;
2287 mDownTime = 0;
2288 mKeyDowns.clear();
2289 mCurrentHidUsage = 0;
2290
2291 resetLedState();
2292
2293 InputMapper::reset(when);
2294}
2295
2296void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2297 switch (rawEvent->type) {
2298 case EV_KEY: {
2299 int32_t scanCode = rawEvent->code;
2300 int32_t usageCode = mCurrentHidUsage;
2301 mCurrentHidUsage = 0;
2302
2303 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002304 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306 break;
2307 }
2308 case EV_MSC: {
2309 if (rawEvent->code == MSC_SCAN) {
2310 mCurrentHidUsage = rawEvent->value;
2311 }
2312 break;
2313 }
2314 case EV_SYN: {
2315 if (rawEvent->code == SYN_REPORT) {
2316 mCurrentHidUsage = 0;
2317 }
2318 }
2319 }
2320}
2321
2322bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2323 return scanCode < BTN_MOUSE
2324 || scanCode >= KEY_OK
2325 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2326 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2327}
2328
Michael Wright58ba9882017-07-26 16:19:11 +01002329bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2330 switch (keyCode) {
2331 case AKEYCODE_MEDIA_PLAY:
2332 case AKEYCODE_MEDIA_PAUSE:
2333 case AKEYCODE_MEDIA_PLAY_PAUSE:
2334 case AKEYCODE_MUTE:
2335 case AKEYCODE_HEADSETHOOK:
2336 case AKEYCODE_MEDIA_STOP:
2337 case AKEYCODE_MEDIA_NEXT:
2338 case AKEYCODE_MEDIA_PREVIOUS:
2339 case AKEYCODE_MEDIA_REWIND:
2340 case AKEYCODE_MEDIA_RECORD:
2341 case AKEYCODE_MEDIA_FAST_FORWARD:
2342 case AKEYCODE_MEDIA_SKIP_FORWARD:
2343 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2344 case AKEYCODE_MEDIA_STEP_FORWARD:
2345 case AKEYCODE_MEDIA_STEP_BACKWARD:
2346 case AKEYCODE_MEDIA_AUDIO_TRACK:
2347 case AKEYCODE_VOLUME_UP:
2348 case AKEYCODE_VOLUME_DOWN:
2349 case AKEYCODE_VOLUME_MUTE:
2350 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2351 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2352 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2353 return true;
2354 }
2355 return false;
2356}
2357
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002358void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2359 int32_t usageCode) {
2360 int32_t keyCode;
2361 int32_t keyMetaState;
2362 uint32_t policyFlags;
2363
2364 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2365 &keyCode, &keyMetaState, &policyFlags)) {
2366 keyCode = AKEYCODE_UNKNOWN;
2367 keyMetaState = mMetaState;
2368 policyFlags = 0;
2369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370
2371 if (down) {
2372 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002373 if (mParameters.orientationAware) {
2374 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
2377 // Add key down.
2378 ssize_t keyDownIndex = findKeyDown(scanCode);
2379 if (keyDownIndex >= 0) {
2380 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002381 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 } else {
2383 // key down
2384 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2385 && mContext->shouldDropVirtualKey(when,
2386 getDevice(), keyCode, scanCode)) {
2387 return;
2388 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002389 if (policyFlags & POLICY_FLAG_GESTURE) {
2390 mDevice->cancelTouch(when);
2391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002393 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 keyDown.keyCode = keyCode;
2395 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002396 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 }
2398
2399 mDownTime = when;
2400 } else {
2401 // Remove key down.
2402 ssize_t keyDownIndex = findKeyDown(scanCode);
2403 if (keyDownIndex >= 0) {
2404 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002405 keyCode = mKeyDowns[keyDownIndex].keyCode;
2406 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 } else {
2408 // key was not actually down
2409 ALOGI("Dropping key up from device %s because the key was not down. "
2410 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002411 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 return;
2413 }
2414 }
2415
Andrii Kulian763a3a42016-03-08 10:46:16 -08002416 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002417 // If global meta state changed send it along with the key.
2418 // If it has not changed then we'll use what keymap gave us,
2419 // since key replacement logic might temporarily reset a few
2420 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002421 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
2424 nsecs_t downTime = mDownTime;
2425
2426 // Key down on external an keyboard should wake the device.
2427 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2428 // For internal keyboards, the key layout file should specify the policy flags for
2429 // each wake key individually.
2430 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002431 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002432 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002435 if (mParameters.handlesKeyRepeat) {
2436 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2437 }
2438
Prabir Pradhan42611e02018-11-27 14:04:02 -08002439 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2440 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002441 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 getListener()->notifyKey(&args);
2443}
2444
2445ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2446 size_t n = mKeyDowns.size();
2447 for (size_t i = 0; i < n; i++) {
2448 if (mKeyDowns[i].scanCode == scanCode) {
2449 return i;
2450 }
2451 }
2452 return -1;
2453}
2454
2455int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2456 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2457}
2458
2459int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2460 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2461}
2462
2463bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2464 const int32_t* keyCodes, uint8_t* outFlags) {
2465 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2466}
2467
2468int32_t KeyboardInputMapper::getMetaState() {
2469 return mMetaState;
2470}
2471
Andrii Kulian763a3a42016-03-08 10:46:16 -08002472void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2473 updateMetaStateIfNeeded(keyCode, false);
2474}
2475
2476bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2477 int32_t oldMetaState = mMetaState;
2478 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2479 bool metaStateChanged = oldMetaState != newMetaState;
2480 if (metaStateChanged) {
2481 mMetaState = newMetaState;
2482 updateLedState(false);
2483
2484 getContext()->updateGlobalMetaState();
2485 }
2486
2487 return metaStateChanged;
2488}
2489
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490void KeyboardInputMapper::resetLedState() {
2491 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2492 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2493 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2494
2495 updateLedState(true);
2496}
2497
2498void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2499 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2500 ledState.on = false;
2501}
2502
2503void KeyboardInputMapper::updateLedState(bool reset) {
2504 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2505 AMETA_CAPS_LOCK_ON, reset);
2506 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2507 AMETA_NUM_LOCK_ON, reset);
2508 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2509 AMETA_SCROLL_LOCK_ON, reset);
2510}
2511
2512void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2513 int32_t led, int32_t modifier, bool reset) {
2514 if (ledState.avail) {
2515 bool desiredState = (mMetaState & modifier) != 0;
2516 if (reset || ledState.on != desiredState) {
2517 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2518 ledState.on = desiredState;
2519 }
2520 }
2521}
2522
2523
2524// --- CursorInputMapper ---
2525
2526CursorInputMapper::CursorInputMapper(InputDevice* device) :
2527 InputMapper(device) {
2528}
2529
2530CursorInputMapper::~CursorInputMapper() {
2531}
2532
2533uint32_t CursorInputMapper::getSources() {
2534 return mSource;
2535}
2536
2537void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2538 InputMapper::populateDeviceInfo(info);
2539
2540 if (mParameters.mode == Parameters::MODE_POINTER) {
2541 float minX, minY, maxX, maxY;
2542 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2543 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2544 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2545 }
2546 } else {
2547 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2548 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2549 }
2550 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2551
2552 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2553 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2554 }
2555 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2556 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2557 }
2558}
2559
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002560void CursorInputMapper::dump(std::string& dump) {
2561 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002563 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2564 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2565 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2566 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2567 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002569 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002571 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2572 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2573 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2574 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2575 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2576 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577}
2578
2579void CursorInputMapper::configure(nsecs_t when,
2580 const InputReaderConfiguration* config, uint32_t changes) {
2581 InputMapper::configure(when, config, changes);
2582
2583 if (!changes) { // first time only
2584 mCursorScrollAccumulator.configure(getDevice());
2585
2586 // Configure basic parameters.
2587 configureParameters();
2588
2589 // Configure device mode.
2590 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002591 case Parameters::MODE_POINTER_RELATIVE:
2592 // Should not happen during first time configuration.
2593 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2594 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002595 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 case Parameters::MODE_POINTER:
2597 mSource = AINPUT_SOURCE_MOUSE;
2598 mXPrecision = 1.0f;
2599 mYPrecision = 1.0f;
2600 mXScale = 1.0f;
2601 mYScale = 1.0f;
2602 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2603 break;
2604 case Parameters::MODE_NAVIGATION:
2605 mSource = AINPUT_SOURCE_TRACKBALL;
2606 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2607 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2608 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2609 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2610 break;
2611 }
2612
2613 mVWheelScale = 1.0f;
2614 mHWheelScale = 1.0f;
2615 }
2616
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002617 if ((!changes && config->pointerCapture)
2618 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2619 if (config->pointerCapture) {
2620 if (mParameters.mode == Parameters::MODE_POINTER) {
2621 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2622 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2623 // Keep PointerController around in order to preserve the pointer position.
2624 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2625 } else {
2626 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2627 }
2628 } else {
2629 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2630 mParameters.mode = Parameters::MODE_POINTER;
2631 mSource = AINPUT_SOURCE_MOUSE;
2632 } else {
2633 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2634 }
2635 }
2636 bumpGeneration();
2637 if (changes) {
2638 getDevice()->notifyReset(when);
2639 }
2640 }
2641
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2643 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2644 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2645 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2646 }
2647
2648 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002649 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002651 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002652 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002653 if (internalViewport) {
2654 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002657
2658 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002659 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002660 getPolicy()->obtainPointerController(getDeviceId());
2661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 bumpGeneration();
2663 }
2664}
2665
2666void CursorInputMapper::configureParameters() {
2667 mParameters.mode = Parameters::MODE_POINTER;
2668 String8 cursorModeString;
2669 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2670 if (cursorModeString == "navigation") {
2671 mParameters.mode = Parameters::MODE_NAVIGATION;
2672 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2673 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2674 }
2675 }
2676
2677 mParameters.orientationAware = false;
2678 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2679 mParameters.orientationAware);
2680
2681 mParameters.hasAssociatedDisplay = false;
2682 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2683 mParameters.hasAssociatedDisplay = true;
2684 }
2685}
2686
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002687void CursorInputMapper::dumpParameters(std::string& dump) {
2688 dump += INDENT3 "Parameters:\n";
2689 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 toString(mParameters.hasAssociatedDisplay));
2691
2692 switch (mParameters.mode) {
2693 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002694 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002696 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002697 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002700 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 break;
2702 default:
2703 ALOG_ASSERT(false);
2704 }
2705
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002706 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 toString(mParameters.orientationAware));
2708}
2709
2710void CursorInputMapper::reset(nsecs_t when) {
2711 mButtonState = 0;
2712 mDownTime = 0;
2713
2714 mPointerVelocityControl.reset();
2715 mWheelXVelocityControl.reset();
2716 mWheelYVelocityControl.reset();
2717
2718 mCursorButtonAccumulator.reset(getDevice());
2719 mCursorMotionAccumulator.reset(getDevice());
2720 mCursorScrollAccumulator.reset(getDevice());
2721
2722 InputMapper::reset(when);
2723}
2724
2725void CursorInputMapper::process(const RawEvent* rawEvent) {
2726 mCursorButtonAccumulator.process(rawEvent);
2727 mCursorMotionAccumulator.process(rawEvent);
2728 mCursorScrollAccumulator.process(rawEvent);
2729
2730 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2731 sync(rawEvent->when);
2732 }
2733}
2734
2735void CursorInputMapper::sync(nsecs_t when) {
2736 int32_t lastButtonState = mButtonState;
2737 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2738 mButtonState = currentButtonState;
2739
2740 bool wasDown = isPointerDown(lastButtonState);
2741 bool down = isPointerDown(currentButtonState);
2742 bool downChanged;
2743 if (!wasDown && down) {
2744 mDownTime = when;
2745 downChanged = true;
2746 } else if (wasDown && !down) {
2747 downChanged = true;
2748 } else {
2749 downChanged = false;
2750 }
2751 nsecs_t downTime = mDownTime;
2752 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002753 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2754 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
2756 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2757 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2758 bool moved = deltaX != 0 || deltaY != 0;
2759
2760 // Rotate delta according to orientation if needed.
2761 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2762 && (deltaX != 0.0f || deltaY != 0.0f)) {
2763 rotateDelta(mOrientation, &deltaX, &deltaY);
2764 }
2765
2766 // Move the pointer.
2767 PointerProperties pointerProperties;
2768 pointerProperties.clear();
2769 pointerProperties.id = 0;
2770 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2771
2772 PointerCoords pointerCoords;
2773 pointerCoords.clear();
2774
2775 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2776 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2777 bool scrolled = vscroll != 0 || hscroll != 0;
2778
Yi Kong9b14ac62018-07-17 13:48:38 -07002779 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2780 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781
2782 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2783
2784 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002785 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2786 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002787 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 if (moved || scrolled || buttonsChanged) {
2789 mPointerController->setPresentation(
2790 PointerControllerInterface::PRESENTATION_POINTER);
2791
2792 if (moved) {
2793 mPointerController->move(deltaX, deltaY);
2794 }
2795
2796 if (buttonsChanged) {
2797 mPointerController->setButtonState(currentButtonState);
2798 }
2799
2800 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2801 }
2802
Garfield Tan00f511d2019-06-12 16:55:40 -07002803 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2804 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2807 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002808 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 } else {
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2811 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2812 displayId = ADISPLAY_ID_NONE;
2813 }
2814
2815 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2816
2817 // Moving an external trackball or mouse should wake the device.
2818 // We don't do this for internal cursor devices to prevent them from waking up
2819 // the device in your pocket.
2820 // TODO: Use the input device configuration to control this behavior more finely.
2821 uint32_t policyFlags = 0;
2822 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002823 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825
2826 // Synthesize key down from buttons if needed.
2827 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002828 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829
2830 // Send motion event.
2831 if (downChanged || moved || scrolled || buttonsChanged) {
2832 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002833 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 int32_t motionEventAction;
2835 if (downChanged) {
2836 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002837 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2839 } else {
2840 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2841 }
2842
Michael Wright7b159c92015-05-14 14:48:03 +01002843 if (buttonsReleased) {
2844 BitSet32 released(buttonsReleased);
2845 while (!released.isEmpty()) {
2846 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2847 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002848 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002849 mSource, displayId, policyFlags,
2850 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2851 metaState, buttonState, MotionClassification::NONE,
2852 AMOTION_EVENT_EDGE_FLAG_NONE,
2853 /* deviceTimestamp */ 0, 1, &pointerProperties,
2854 &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,
2864 AMOTION_EVENT_EDGE_FLAG_NONE,
2865 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
2866 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2867 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002868 getListener()->notifyMotion(&args);
2869
Michael Wright7b159c92015-05-14 14:48:03 +01002870 if (buttonsPressed) {
2871 BitSet32 pressed(buttonsPressed);
2872 while (!pressed.isEmpty()) {
2873 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2874 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002875 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002876 mSource, displayId, policyFlags,
2877 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2878 metaState, buttonState, MotionClassification::NONE,
2879 AMOTION_EVENT_EDGE_FLAG_NONE,
2880 /* deviceTimestamp */ 0, 1, &pointerProperties,
2881 &pointerCoords, mXPrecision, mYPrecision,
2882 xCursorPosition, yCursorPosition, downTime,
2883 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002884 getListener()->notifyMotion(&pressArgs);
2885 }
2886 }
2887
2888 ALOG_ASSERT(buttonState == currentButtonState);
2889
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 // Send hover move after UP to tell the application that the mouse is hovering now.
2891 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002892 && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002893 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2894 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2895 0, metaState, currentButtonState, MotionClassification::NONE,
2896 AMOTION_EVENT_EDGE_FLAG_NONE,
2897 /* deviceTimestamp */ 0, 1, &pointerProperties,
2898 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
2899 yCursorPosition, downTime,
2900 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 getListener()->notifyMotion(&hoverArgs);
2902 }
2903
2904 // Send scroll events.
2905 if (scrolled) {
2906 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2907 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2908
Prabir Pradhan42611e02018-11-27 14:04:02 -08002909 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002910 mSource, displayId, policyFlags,
2911 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2912 currentButtonState, MotionClassification::NONE,
2913 AMOTION_EVENT_EDGE_FLAG_NONE,
2914 /* deviceTimestamp */ 0, 1, &pointerProperties,
2915 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
2916 yCursorPosition, downTime,
2917 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 getListener()->notifyMotion(&scrollArgs);
2919 }
2920 }
2921
2922 // Synthesize key up from buttons if needed.
2923 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002924 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002925
2926 mCursorMotionAccumulator.finishSync();
2927 mCursorScrollAccumulator.finishSync();
2928}
2929
2930int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2931 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2932 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2933 } else {
2934 return AKEY_STATE_UNKNOWN;
2935 }
2936}
2937
2938void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002939 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002940 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2941 }
2942}
2943
Arthur Hungc23540e2018-11-29 20:42:11 +08002944std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2945 if (mParameters.hasAssociatedDisplay) {
2946 if (mParameters.mode == Parameters::MODE_POINTER) {
2947 return std::make_optional(mPointerController->getDisplayId());
2948 } else {
2949 // If the device is orientationAware and not a mouse,
2950 // it expects to dispatch events to any display
2951 return std::make_optional(ADISPLAY_ID_NONE);
2952 }
2953 }
2954 return std::nullopt;
2955}
2956
Prashant Malani1941ff52015-08-11 18:29:28 -07002957// --- RotaryEncoderInputMapper ---
2958
2959RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002960 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002961 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2962}
2963
2964RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2965}
2966
2967uint32_t RotaryEncoderInputMapper::getSources() {
2968 return mSource;
2969}
2970
2971void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2972 InputMapper::populateDeviceInfo(info);
2973
2974 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002975 float res = 0.0f;
2976 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2977 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2978 }
2979 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2980 mScalingFactor)) {
2981 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2982 "default to 1.0!\n");
2983 mScalingFactor = 1.0f;
2984 }
2985 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2986 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002987 }
2988}
2989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002990void RotaryEncoderInputMapper::dump(std::string& dump) {
2991 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2992 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002993 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2994}
2995
2996void RotaryEncoderInputMapper::configure(nsecs_t when,
2997 const InputReaderConfiguration* config, uint32_t changes) {
2998 InputMapper::configure(when, config, changes);
2999 if (!changes) {
3000 mRotaryEncoderScrollAccumulator.configure(getDevice());
3001 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003002 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003003 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003004 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003005 if (internalViewport) {
3006 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003007 } else {
3008 mOrientation = DISPLAY_ORIENTATION_0;
3009 }
3010 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003011}
3012
3013void RotaryEncoderInputMapper::reset(nsecs_t when) {
3014 mRotaryEncoderScrollAccumulator.reset(getDevice());
3015
3016 InputMapper::reset(when);
3017}
3018
3019void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3020 mRotaryEncoderScrollAccumulator.process(rawEvent);
3021
3022 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3023 sync(rawEvent->when);
3024 }
3025}
3026
3027void RotaryEncoderInputMapper::sync(nsecs_t when) {
3028 PointerCoords pointerCoords;
3029 pointerCoords.clear();
3030
3031 PointerProperties pointerProperties;
3032 pointerProperties.clear();
3033 pointerProperties.id = 0;
3034 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3035
3036 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3037 bool scrolled = scroll != 0;
3038
3039 // This is not a pointer, so it's not associated with a display.
3040 int32_t displayId = ADISPLAY_ID_NONE;
3041
3042 // Moving the rotary encoder should wake the device (if specified).
3043 uint32_t policyFlags = 0;
3044 if (scrolled && getDevice()->isExternal()) {
3045 policyFlags |= POLICY_FLAG_WAKE;
3046 }
3047
Ivan Podogovad437252016-09-29 16:29:55 +01003048 if (mOrientation == DISPLAY_ORIENTATION_180) {
3049 scroll = -scroll;
3050 }
3051
Prashant Malani1941ff52015-08-11 18:29:28 -07003052 // Send motion event.
3053 if (scrolled) {
3054 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003055 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003056
Garfield Tan00f511d2019-06-12 16:55:40 -07003057 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3058 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3059 metaState, /* buttonState */ 0, MotionClassification::NONE,
3060 AMOTION_EVENT_EDGE_FLAG_NONE,
3061 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
3062 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
3063 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003064 getListener()->notifyMotion(&scrollArgs);
3065 }
3066
3067 mRotaryEncoderScrollAccumulator.finishSync();
3068}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069
3070// --- TouchInputMapper ---
3071
3072TouchInputMapper::TouchInputMapper(InputDevice* device) :
3073 InputMapper(device),
3074 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3075 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003076 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003077 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3078}
3079
3080TouchInputMapper::~TouchInputMapper() {
3081}
3082
3083uint32_t TouchInputMapper::getSources() {
3084 return mSource;
3085}
3086
3087void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3088 InputMapper::populateDeviceInfo(info);
3089
3090 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3091 info->addMotionRange(mOrientedRanges.x);
3092 info->addMotionRange(mOrientedRanges.y);
3093 info->addMotionRange(mOrientedRanges.pressure);
3094
3095 if (mOrientedRanges.haveSize) {
3096 info->addMotionRange(mOrientedRanges.size);
3097 }
3098
3099 if (mOrientedRanges.haveTouchSize) {
3100 info->addMotionRange(mOrientedRanges.touchMajor);
3101 info->addMotionRange(mOrientedRanges.touchMinor);
3102 }
3103
3104 if (mOrientedRanges.haveToolSize) {
3105 info->addMotionRange(mOrientedRanges.toolMajor);
3106 info->addMotionRange(mOrientedRanges.toolMinor);
3107 }
3108
3109 if (mOrientedRanges.haveOrientation) {
3110 info->addMotionRange(mOrientedRanges.orientation);
3111 }
3112
3113 if (mOrientedRanges.haveDistance) {
3114 info->addMotionRange(mOrientedRanges.distance);
3115 }
3116
3117 if (mOrientedRanges.haveTilt) {
3118 info->addMotionRange(mOrientedRanges.tilt);
3119 }
3120
3121 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3122 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3123 0.0f);
3124 }
3125 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3126 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3127 0.0f);
3128 }
3129 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3130 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3131 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3132 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3133 x.fuzz, x.resolution);
3134 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3135 y.fuzz, y.resolution);
3136 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3137 x.fuzz, x.resolution);
3138 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3139 y.fuzz, y.resolution);
3140 }
3141 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3142 }
3143}
3144
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003145void TouchInputMapper::dump(std::string& dump) {
3146 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003147 dumpParameters(dump);
3148 dumpVirtualKeys(dump);
3149 dumpRawPointerAxes(dump);
3150 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003151 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 dumpSurface(dump);
3153
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003154 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3155 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3156 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3157 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3158 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3159 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3160 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3161 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3162 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3163 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3164 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3165 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3166 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3167 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3168 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3169 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3170 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003171
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003172 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3173 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003174 mLastRawState.rawPointerData.pointerCount);
3175 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3176 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3179 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3180 "toolType=%d, isHovering=%s\n", i,
3181 pointer.id, pointer.x, pointer.y, pointer.pressure,
3182 pointer.touchMajor, pointer.touchMinor,
3183 pointer.toolMajor, pointer.toolMinor,
3184 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3185 pointer.toolType, toString(pointer.isHovering));
3186 }
3187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3189 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003190 mLastCookedState.cookedPointerData.pointerCount);
3191 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3192 const PointerProperties& pointerProperties =
3193 mLastCookedState.cookedPointerData.pointerProperties[i];
3194 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003195 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3197 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3198 "toolType=%d, isHovering=%s\n", i,
3199 pointerProperties.id,
3200 pointerCoords.getX(),
3201 pointerCoords.getY(),
3202 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3203 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3204 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3205 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3206 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3207 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3208 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3209 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3210 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003211 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 }
3213
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003214 dump += INDENT3 "Stylus Fusion:\n";
3215 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003216 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3218 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003219 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003221 dumpStylusState(dump, mExternalStylusState);
3222
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003224 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3225 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003227 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003228 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003229 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003231 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003232 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003233 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003234 mPointerGestureMaxSwipeWidth);
3235 }
3236}
3237
Santos Cordonfa5cf462017-04-05 10:37:00 -07003238const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3239 switch (deviceMode) {
3240 case DEVICE_MODE_DISABLED:
3241 return "disabled";
3242 case DEVICE_MODE_DIRECT:
3243 return "direct";
3244 case DEVICE_MODE_UNSCALED:
3245 return "unscaled";
3246 case DEVICE_MODE_NAVIGATION:
3247 return "navigation";
3248 case DEVICE_MODE_POINTER:
3249 return "pointer";
3250 }
3251 return "unknown";
3252}
3253
Michael Wrightd02c5b62014-02-10 15:10:22 -08003254void TouchInputMapper::configure(nsecs_t when,
3255 const InputReaderConfiguration* config, uint32_t changes) {
3256 InputMapper::configure(when, config, changes);
3257
3258 mConfig = *config;
3259
3260 if (!changes) { // first time only
3261 // Configure basic parameters.
3262 configureParameters();
3263
3264 // Configure common accumulators.
3265 mCursorScrollAccumulator.configure(getDevice());
3266 mTouchButtonAccumulator.configure(getDevice());
3267
3268 // Configure absolute axis information.
3269 configureRawPointerAxes();
3270
3271 // Prepare input device calibration.
3272 parseCalibration();
3273 resolveCalibration();
3274 }
3275
Michael Wright842500e2015-03-13 17:32:02 -07003276 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003277 // Update location calibration to reflect current settings
3278 updateAffineTransformation();
3279 }
3280
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3282 // Update pointer speed.
3283 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3284 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3285 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3286 }
3287
3288 bool resetNeeded = false;
3289 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3290 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003291 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3292 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 // Configure device sources, surface dimensions, orientation and
3294 // scaling factors.
3295 configureSurface(when, &resetNeeded);
3296 }
3297
3298 if (changes && resetNeeded) {
3299 // Send reset, unless this is the first time the device has been configured,
3300 // in which case the reader will call reset itself after all mappers are ready.
3301 getDevice()->notifyReset(when);
3302 }
3303}
3304
Michael Wright842500e2015-03-13 17:32:02 -07003305void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003306 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003307 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003308 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003309
3310 if (!mExternalStylusConnected) {
3311 resetExternalStylus();
3312 }
3313}
3314
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315void TouchInputMapper::configureParameters() {
3316 // Use the pointer presentation mode for devices that do not support distinct
3317 // multitouch. The spot-based presentation relies on being able to accurately
3318 // locate two or more fingers on the touch pad.
3319 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003320 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321
3322 String8 gestureModeString;
3323 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3324 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003325 if (gestureModeString == "single-touch") {
3326 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3327 } else if (gestureModeString == "multi-touch") {
3328 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003329 } else if (gestureModeString != "default") {
3330 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3331 }
3332 }
3333
3334 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3335 // The device is a touch screen.
3336 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3337 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3338 // The device is a pointing device like a track pad.
3339 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3340 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3341 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3342 // The device is a cursor device with a touch pad attached.
3343 // By default don't use the touch pad to move the pointer.
3344 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3345 } else {
3346 // The device is a touch pad of unknown purpose.
3347 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3348 }
3349
3350 mParameters.hasButtonUnderPad=
3351 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3352
3353 String8 deviceTypeString;
3354 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3355 deviceTypeString)) {
3356 if (deviceTypeString == "touchScreen") {
3357 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3358 } else if (deviceTypeString == "touchPad") {
3359 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3360 } else if (deviceTypeString == "touchNavigation") {
3361 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3362 } else if (deviceTypeString == "pointer") {
3363 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3364 } else if (deviceTypeString != "default") {
3365 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3366 }
3367 }
3368
3369 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3370 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3371 mParameters.orientationAware);
3372
3373 mParameters.hasAssociatedDisplay = false;
3374 mParameters.associatedDisplayIsExternal = false;
3375 if (mParameters.orientationAware
3376 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3377 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3378 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003379 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3380 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003381 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003382 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003383 uniqueDisplayId);
3384 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003387 if (getDevice()->getAssociatedDisplayPort()) {
3388 mParameters.hasAssociatedDisplay = true;
3389 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003390
3391 // Initial downs on external touch devices should wake the device.
3392 // Normally we don't do this for internal touch screens to prevent them from waking
3393 // up in your pocket but you can enable it using the input device configuration.
3394 mParameters.wake = getDevice()->isExternal();
3395 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3396 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397}
3398
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003399void TouchInputMapper::dumpParameters(std::string& dump) {
3400 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401
3402 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003403 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003404 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003406 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 break;
3409 default:
3410 assert(false);
3411 }
3412
3413 switch (mParameters.deviceType) {
3414 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 break;
3417 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003418 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 break;
3420 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 break;
3423 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003424 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003425 break;
3426 default:
3427 ALOG_ASSERT(false);
3428 }
3429
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003430 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003431 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003433 toString(mParameters.associatedDisplayIsExternal),
3434 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 toString(mParameters.orientationAware));
3437}
3438
3439void TouchInputMapper::configureRawPointerAxes() {
3440 mRawPointerAxes.clear();
3441}
3442
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003443void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3444 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3446 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3447 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3458}
3459
Michael Wright842500e2015-03-13 17:32:02 -07003460bool TouchInputMapper::hasExternalStylus() const {
3461 return mExternalStylusConnected;
3462}
3463
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003464/**
3465 * Determine which DisplayViewport to use.
3466 * 1. If display port is specified, return the matching viewport. If matching viewport not
3467 * found, then return.
3468 * 2. If a device has associated display, get the matching viewport by either unique id or by
3469 * the display type (internal or external).
3470 * 3. Otherwise, use a non-display viewport.
3471 */
3472std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3473 if (mParameters.hasAssociatedDisplay) {
3474 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3475 if (displayPort) {
3476 // Find the viewport that contains the same port
3477 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3478 if (!v) {
3479 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3480 "but the corresponding viewport is not found.",
3481 getDeviceName().c_str(), *displayPort);
3482 }
3483 return v;
3484 }
3485
3486 if (!mParameters.uniqueDisplayId.empty()) {
3487 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3488 }
3489
3490 ViewportType viewportTypeToUse;
3491 if (mParameters.associatedDisplayIsExternal) {
3492 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3493 } else {
3494 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3495 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003496
3497 std::optional<DisplayViewport> viewport =
3498 mConfig.getDisplayViewportByType(viewportTypeToUse);
3499 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3500 ALOGW("Input device %s should be associated with external display, "
3501 "fallback to internal one for the external viewport is not found.",
3502 getDeviceName().c_str());
3503 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3504 }
3505
3506 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003507 }
3508
3509 DisplayViewport newViewport;
3510 // Raw width and height in the natural orientation.
3511 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3512 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3513 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3514 return std::make_optional(newViewport);
3515}
3516
Michael Wrightd02c5b62014-02-10 15:10:22 -08003517void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3518 int32_t oldDeviceMode = mDeviceMode;
3519
Michael Wright842500e2015-03-13 17:32:02 -07003520 resolveExternalStylusPresence();
3521
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522 // Determine device mode.
3523 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3524 && mConfig.pointerGesturesEnabled) {
3525 mSource = AINPUT_SOURCE_MOUSE;
3526 mDeviceMode = DEVICE_MODE_POINTER;
3527 if (hasStylus()) {
3528 mSource |= AINPUT_SOURCE_STYLUS;
3529 }
3530 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3531 && mParameters.hasAssociatedDisplay) {
3532 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3533 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003534 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 mSource |= AINPUT_SOURCE_STYLUS;
3536 }
Michael Wright2f78b682015-06-12 15:25:08 +01003537 if (hasExternalStylus()) {
3538 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3539 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003540 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3541 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3542 mDeviceMode = DEVICE_MODE_NAVIGATION;
3543 } else {
3544 mSource = AINPUT_SOURCE_TOUCHPAD;
3545 mDeviceMode = DEVICE_MODE_UNSCALED;
3546 }
3547
3548 // Ensure we have valid X and Y axes.
3549 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003550 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003551 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 mDeviceMode = DEVICE_MODE_DISABLED;
3553 return;
3554 }
3555
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003556 // Get associated display dimensions.
3557 std::optional<DisplayViewport> newViewport = findViewport();
3558 if (!newViewport) {
3559 ALOGI("Touch device '%s' could not query the properties of its associated "
3560 "display. The device will be inoperable until the display size "
3561 "becomes available.",
3562 getDeviceName().c_str());
3563 mDeviceMode = DEVICE_MODE_DISABLED;
3564 return;
3565 }
3566
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003568 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3569 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003571 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003573 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574
3575 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3576 // Convert rotated viewport to natural surface coordinates.
3577 int32_t naturalLogicalWidth, naturalLogicalHeight;
3578 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3579 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3580 int32_t naturalDeviceWidth, naturalDeviceHeight;
3581 switch (mViewport.orientation) {
3582 case DISPLAY_ORIENTATION_90:
3583 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3584 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3585 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3586 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3587 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3588 naturalPhysicalTop = mViewport.physicalLeft;
3589 naturalDeviceWidth = mViewport.deviceHeight;
3590 naturalDeviceHeight = mViewport.deviceWidth;
3591 break;
3592 case DISPLAY_ORIENTATION_180:
3593 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3594 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3595 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3596 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3597 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3598 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3599 naturalDeviceWidth = mViewport.deviceWidth;
3600 naturalDeviceHeight = mViewport.deviceHeight;
3601 break;
3602 case DISPLAY_ORIENTATION_270:
3603 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3604 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3605 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3606 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3607 naturalPhysicalLeft = mViewport.physicalTop;
3608 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3609 naturalDeviceWidth = mViewport.deviceHeight;
3610 naturalDeviceHeight = mViewport.deviceWidth;
3611 break;
3612 case DISPLAY_ORIENTATION_0:
3613 default:
3614 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3615 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3616 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3617 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3618 naturalPhysicalLeft = mViewport.physicalLeft;
3619 naturalPhysicalTop = mViewport.physicalTop;
3620 naturalDeviceWidth = mViewport.deviceWidth;
3621 naturalDeviceHeight = mViewport.deviceHeight;
3622 break;
3623 }
3624
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003625 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3626 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3627 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3628 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3629 }
3630
Michael Wright358bcc72018-08-21 04:01:07 +01003631 mPhysicalWidth = naturalPhysicalWidth;
3632 mPhysicalHeight = naturalPhysicalHeight;
3633 mPhysicalLeft = naturalPhysicalLeft;
3634 mPhysicalTop = naturalPhysicalTop;
3635
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3637 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3638 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3639 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3640
3641 mSurfaceOrientation = mParameters.orientationAware ?
3642 mViewport.orientation : DISPLAY_ORIENTATION_0;
3643 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003644 mPhysicalWidth = rawWidth;
3645 mPhysicalHeight = rawHeight;
3646 mPhysicalLeft = 0;
3647 mPhysicalTop = 0;
3648
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 mSurfaceWidth = rawWidth;
3650 mSurfaceHeight = rawHeight;
3651 mSurfaceLeft = 0;
3652 mSurfaceTop = 0;
3653 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3654 }
3655 }
3656
3657 // If moving between pointer modes, need to reset some state.
3658 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3659 if (deviceModeChanged) {
3660 mOrientedRanges.clear();
3661 }
3662
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003663 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 if (mDeviceMode == DEVICE_MODE_POINTER ||
3665 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003666 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3668 }
3669 } else {
3670 mPointerController.clear();
3671 }
3672
3673 if (viewportChanged || deviceModeChanged) {
3674 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3675 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003676 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3678
3679 // Configure X and Y factors.
3680 mXScale = float(mSurfaceWidth) / rawWidth;
3681 mYScale = float(mSurfaceHeight) / rawHeight;
3682 mXTranslate = -mSurfaceLeft;
3683 mYTranslate = -mSurfaceTop;
3684 mXPrecision = 1.0f / mXScale;
3685 mYPrecision = 1.0f / mYScale;
3686
3687 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3688 mOrientedRanges.x.source = mSource;
3689 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3690 mOrientedRanges.y.source = mSource;
3691
3692 configureVirtualKeys();
3693
3694 // Scale factor for terms that are not oriented in a particular axis.
3695 // If the pixels are square then xScale == yScale otherwise we fake it
3696 // by choosing an average.
3697 mGeometricScale = avg(mXScale, mYScale);
3698
3699 // Size of diagonal axis.
3700 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3701
3702 // Size factors.
3703 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3704 if (mRawPointerAxes.touchMajor.valid
3705 && mRawPointerAxes.touchMajor.maxValue != 0) {
3706 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3707 } else if (mRawPointerAxes.toolMajor.valid
3708 && mRawPointerAxes.toolMajor.maxValue != 0) {
3709 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3710 } else {
3711 mSizeScale = 0.0f;
3712 }
3713
3714 mOrientedRanges.haveTouchSize = true;
3715 mOrientedRanges.haveToolSize = true;
3716 mOrientedRanges.haveSize = true;
3717
3718 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3719 mOrientedRanges.touchMajor.source = mSource;
3720 mOrientedRanges.touchMajor.min = 0;
3721 mOrientedRanges.touchMajor.max = diagonalSize;
3722 mOrientedRanges.touchMajor.flat = 0;
3723 mOrientedRanges.touchMajor.fuzz = 0;
3724 mOrientedRanges.touchMajor.resolution = 0;
3725
3726 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3727 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3728
3729 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3730 mOrientedRanges.toolMajor.source = mSource;
3731 mOrientedRanges.toolMajor.min = 0;
3732 mOrientedRanges.toolMajor.max = diagonalSize;
3733 mOrientedRanges.toolMajor.flat = 0;
3734 mOrientedRanges.toolMajor.fuzz = 0;
3735 mOrientedRanges.toolMajor.resolution = 0;
3736
3737 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3738 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3739
3740 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3741 mOrientedRanges.size.source = mSource;
3742 mOrientedRanges.size.min = 0;
3743 mOrientedRanges.size.max = 1.0;
3744 mOrientedRanges.size.flat = 0;
3745 mOrientedRanges.size.fuzz = 0;
3746 mOrientedRanges.size.resolution = 0;
3747 } else {
3748 mSizeScale = 0.0f;
3749 }
3750
3751 // Pressure factors.
3752 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003753 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3755 || mCalibration.pressureCalibration
3756 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3757 if (mCalibration.havePressureScale) {
3758 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003759 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003760 } else if (mRawPointerAxes.pressure.valid
3761 && mRawPointerAxes.pressure.maxValue != 0) {
3762 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3763 }
3764 }
3765
3766 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3767 mOrientedRanges.pressure.source = mSource;
3768 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003769 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003770 mOrientedRanges.pressure.flat = 0;
3771 mOrientedRanges.pressure.fuzz = 0;
3772 mOrientedRanges.pressure.resolution = 0;
3773
3774 // Tilt
3775 mTiltXCenter = 0;
3776 mTiltXScale = 0;
3777 mTiltYCenter = 0;
3778 mTiltYScale = 0;
3779 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3780 if (mHaveTilt) {
3781 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3782 mRawPointerAxes.tiltX.maxValue);
3783 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3784 mRawPointerAxes.tiltY.maxValue);
3785 mTiltXScale = M_PI / 180;
3786 mTiltYScale = M_PI / 180;
3787
3788 mOrientedRanges.haveTilt = true;
3789
3790 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3791 mOrientedRanges.tilt.source = mSource;
3792 mOrientedRanges.tilt.min = 0;
3793 mOrientedRanges.tilt.max = M_PI_2;
3794 mOrientedRanges.tilt.flat = 0;
3795 mOrientedRanges.tilt.fuzz = 0;
3796 mOrientedRanges.tilt.resolution = 0;
3797 }
3798
3799 // Orientation
3800 mOrientationScale = 0;
3801 if (mHaveTilt) {
3802 mOrientedRanges.haveOrientation = true;
3803
3804 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3805 mOrientedRanges.orientation.source = mSource;
3806 mOrientedRanges.orientation.min = -M_PI;
3807 mOrientedRanges.orientation.max = M_PI;
3808 mOrientedRanges.orientation.flat = 0;
3809 mOrientedRanges.orientation.fuzz = 0;
3810 mOrientedRanges.orientation.resolution = 0;
3811 } else if (mCalibration.orientationCalibration !=
3812 Calibration::ORIENTATION_CALIBRATION_NONE) {
3813 if (mCalibration.orientationCalibration
3814 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3815 if (mRawPointerAxes.orientation.valid) {
3816 if (mRawPointerAxes.orientation.maxValue > 0) {
3817 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3818 } else if (mRawPointerAxes.orientation.minValue < 0) {
3819 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3820 } else {
3821 mOrientationScale = 0;
3822 }
3823 }
3824 }
3825
3826 mOrientedRanges.haveOrientation = true;
3827
3828 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3829 mOrientedRanges.orientation.source = mSource;
3830 mOrientedRanges.orientation.min = -M_PI_2;
3831 mOrientedRanges.orientation.max = M_PI_2;
3832 mOrientedRanges.orientation.flat = 0;
3833 mOrientedRanges.orientation.fuzz = 0;
3834 mOrientedRanges.orientation.resolution = 0;
3835 }
3836
3837 // Distance
3838 mDistanceScale = 0;
3839 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3840 if (mCalibration.distanceCalibration
3841 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3842 if (mCalibration.haveDistanceScale) {
3843 mDistanceScale = mCalibration.distanceScale;
3844 } else {
3845 mDistanceScale = 1.0f;
3846 }
3847 }
3848
3849 mOrientedRanges.haveDistance = true;
3850
3851 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3852 mOrientedRanges.distance.source = mSource;
3853 mOrientedRanges.distance.min =
3854 mRawPointerAxes.distance.minValue * mDistanceScale;
3855 mOrientedRanges.distance.max =
3856 mRawPointerAxes.distance.maxValue * mDistanceScale;
3857 mOrientedRanges.distance.flat = 0;
3858 mOrientedRanges.distance.fuzz =
3859 mRawPointerAxes.distance.fuzz * mDistanceScale;
3860 mOrientedRanges.distance.resolution = 0;
3861 }
3862
3863 // Compute oriented precision, scales and ranges.
3864 // Note that the maximum value reported is an inclusive maximum value so it is one
3865 // unit less than the total width or height of surface.
3866 switch (mSurfaceOrientation) {
3867 case DISPLAY_ORIENTATION_90:
3868 case DISPLAY_ORIENTATION_270:
3869 mOrientedXPrecision = mYPrecision;
3870 mOrientedYPrecision = mXPrecision;
3871
3872 mOrientedRanges.x.min = mYTranslate;
3873 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3874 mOrientedRanges.x.flat = 0;
3875 mOrientedRanges.x.fuzz = 0;
3876 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3877
3878 mOrientedRanges.y.min = mXTranslate;
3879 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3880 mOrientedRanges.y.flat = 0;
3881 mOrientedRanges.y.fuzz = 0;
3882 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3883 break;
3884
3885 default:
3886 mOrientedXPrecision = mXPrecision;
3887 mOrientedYPrecision = mYPrecision;
3888
3889 mOrientedRanges.x.min = mXTranslate;
3890 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3891 mOrientedRanges.x.flat = 0;
3892 mOrientedRanges.x.fuzz = 0;
3893 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3894
3895 mOrientedRanges.y.min = mYTranslate;
3896 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3897 mOrientedRanges.y.flat = 0;
3898 mOrientedRanges.y.fuzz = 0;
3899 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3900 break;
3901 }
3902
Jason Gerecke71b16e82014-03-10 09:47:59 -07003903 // Location
3904 updateAffineTransformation();
3905
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906 if (mDeviceMode == DEVICE_MODE_POINTER) {
3907 // Compute pointer gesture detection parameters.
3908 float rawDiagonal = hypotf(rawWidth, rawHeight);
3909 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3910
3911 // Scale movements such that one whole swipe of the touch pad covers a
3912 // given area relative to the diagonal size of the display when no acceleration
3913 // is applied.
3914 // Assume that the touch pad has a square aspect ratio such that movements in
3915 // X and Y of the same number of raw units cover the same physical distance.
3916 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3917 * displayDiagonal / rawDiagonal;
3918 mPointerYMovementScale = mPointerXMovementScale;
3919
3920 // Scale zooms to cover a smaller range of the display than movements do.
3921 // This value determines the area around the pointer that is affected by freeform
3922 // pointer gestures.
3923 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3924 * displayDiagonal / rawDiagonal;
3925 mPointerYZoomScale = mPointerXZoomScale;
3926
3927 // Max width between pointers to detect a swipe gesture is more than some fraction
3928 // of the diagonal axis of the touch pad. Touches that are wider than this are
3929 // translated into freeform gestures.
3930 mPointerGestureMaxSwipeWidth =
3931 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3932
3933 // Abort current pointer usages because the state has changed.
3934 abortPointerUsage(when, 0 /*policyFlags*/);
3935 }
3936
3937 // Inform the dispatcher about the changes.
3938 *outResetNeeded = true;
3939 bumpGeneration();
3940 }
3941}
3942
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003943void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003944 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003945 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3946 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3947 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3948 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003949 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3950 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3951 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3952 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003953 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003954}
3955
3956void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003957 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3959
3960 mVirtualKeys.clear();
3961
3962 if (virtualKeyDefinitions.size() == 0) {
3963 return;
3964 }
3965
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3967 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003968 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3969 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003971 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3972 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973
3974 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3975 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003976 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003978 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3979 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3981 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003982 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003983 }
3984
3985 virtualKey.keyCode = keyCode;
3986 virtualKey.flags = flags;
3987
3988 // convert the key definition's display coordinates into touch coordinates for a hit box
3989 int32_t halfWidth = virtualKeyDefinition.width / 2;
3990 int32_t halfHeight = virtualKeyDefinition.height / 2;
3991
3992 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3993 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3994 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3995 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3996 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3997 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3998 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3999 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004000 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004001 }
4002}
4003
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004004void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004005 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004006 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004007
4008 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004009 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004010 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004011 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4012 i, virtualKey.scanCode, virtualKey.keyCode,
4013 virtualKey.hitLeft, virtualKey.hitRight,
4014 virtualKey.hitTop, virtualKey.hitBottom);
4015 }
4016 }
4017}
4018
4019void TouchInputMapper::parseCalibration() {
4020 const PropertyMap& in = getDevice()->getConfiguration();
4021 Calibration& out = mCalibration;
4022
4023 // Size
4024 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4025 String8 sizeCalibrationString;
4026 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4027 if (sizeCalibrationString == "none") {
4028 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4029 } else if (sizeCalibrationString == "geometric") {
4030 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4031 } else if (sizeCalibrationString == "diameter") {
4032 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4033 } else if (sizeCalibrationString == "box") {
4034 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4035 } else if (sizeCalibrationString == "area") {
4036 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4037 } else if (sizeCalibrationString != "default") {
4038 ALOGW("Invalid value for touch.size.calibration: '%s'",
4039 sizeCalibrationString.string());
4040 }
4041 }
4042
4043 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4044 out.sizeScale);
4045 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4046 out.sizeBias);
4047 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4048 out.sizeIsSummed);
4049
4050 // Pressure
4051 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4052 String8 pressureCalibrationString;
4053 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4054 if (pressureCalibrationString == "none") {
4055 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4056 } else if (pressureCalibrationString == "physical") {
4057 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4058 } else if (pressureCalibrationString == "amplitude") {
4059 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4060 } else if (pressureCalibrationString != "default") {
4061 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4062 pressureCalibrationString.string());
4063 }
4064 }
4065
4066 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4067 out.pressureScale);
4068
4069 // Orientation
4070 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4071 String8 orientationCalibrationString;
4072 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4073 if (orientationCalibrationString == "none") {
4074 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4075 } else if (orientationCalibrationString == "interpolated") {
4076 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4077 } else if (orientationCalibrationString == "vector") {
4078 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4079 } else if (orientationCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4081 orientationCalibrationString.string());
4082 }
4083 }
4084
4085 // Distance
4086 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4087 String8 distanceCalibrationString;
4088 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4089 if (distanceCalibrationString == "none") {
4090 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4091 } else if (distanceCalibrationString == "scaled") {
4092 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4093 } else if (distanceCalibrationString != "default") {
4094 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4095 distanceCalibrationString.string());
4096 }
4097 }
4098
4099 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4100 out.distanceScale);
4101
4102 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4103 String8 coverageCalibrationString;
4104 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4105 if (coverageCalibrationString == "none") {
4106 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4107 } else if (coverageCalibrationString == "box") {
4108 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4109 } else if (coverageCalibrationString != "default") {
4110 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4111 coverageCalibrationString.string());
4112 }
4113 }
4114}
4115
4116void TouchInputMapper::resolveCalibration() {
4117 // Size
4118 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4119 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4120 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4121 }
4122 } else {
4123 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4124 }
4125
4126 // Pressure
4127 if (mRawPointerAxes.pressure.valid) {
4128 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4129 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4130 }
4131 } else {
4132 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4133 }
4134
4135 // Orientation
4136 if (mRawPointerAxes.orientation.valid) {
4137 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4138 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4139 }
4140 } else {
4141 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4142 }
4143
4144 // Distance
4145 if (mRawPointerAxes.distance.valid) {
4146 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4147 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4148 }
4149 } else {
4150 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4151 }
4152
4153 // Coverage
4154 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4155 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4156 }
4157}
4158
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159void TouchInputMapper::dumpCalibration(std::string& dump) {
4160 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161
4162 // Size
4163 switch (mCalibration.sizeCalibration) {
4164 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 break;
4170 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 break;
4173 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 break;
4176 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 break;
4179 default:
4180 ALOG_ASSERT(false);
4181 }
4182
4183 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 mCalibration.sizeScale);
4186 }
4187
4188 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 mCalibration.sizeBias);
4191 }
4192
4193 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 toString(mCalibration.sizeIsSummed));
4196 }
4197
4198 // Pressure
4199 switch (mCalibration.pressureCalibration) {
4200 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 break;
4203 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 break;
4206 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 break;
4209 default:
4210 ALOG_ASSERT(false);
4211 }
4212
4213 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004214 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004215 mCalibration.pressureScale);
4216 }
4217
4218 // Orientation
4219 switch (mCalibration.orientationCalibration) {
4220 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 break;
4223 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 break;
4226 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004227 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 break;
4229 default:
4230 ALOG_ASSERT(false);
4231 }
4232
4233 // Distance
4234 switch (mCalibration.distanceCalibration) {
4235 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004236 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 break;
4238 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004239 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 break;
4241 default:
4242 ALOG_ASSERT(false);
4243 }
4244
4245 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 mCalibration.distanceScale);
4248 }
4249
4250 switch (mCalibration.coverageCalibration) {
4251 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004252 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 break;
4254 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 break;
4257 default:
4258 ALOG_ASSERT(false);
4259 }
4260}
4261
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4263 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004264
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4266 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4267 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4268 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4269 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4270 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004271}
4272
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004273void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004274 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4275 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004276}
4277
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278void TouchInputMapper::reset(nsecs_t when) {
4279 mCursorButtonAccumulator.reset(getDevice());
4280 mCursorScrollAccumulator.reset(getDevice());
4281 mTouchButtonAccumulator.reset(getDevice());
4282
4283 mPointerVelocityControl.reset();
4284 mWheelXVelocityControl.reset();
4285 mWheelYVelocityControl.reset();
4286
Michael Wright842500e2015-03-13 17:32:02 -07004287 mRawStatesPending.clear();
4288 mCurrentRawState.clear();
4289 mCurrentCookedState.clear();
4290 mLastRawState.clear();
4291 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004292 mPointerUsage = POINTER_USAGE_NONE;
4293 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004294 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004295 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 mDownTime = 0;
4297
4298 mCurrentVirtualKey.down = false;
4299
4300 mPointerGesture.reset();
4301 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004302 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004303
Yi Kong9b14ac62018-07-17 13:48:38 -07004304 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4306 mPointerController->clearSpots();
4307 }
4308
4309 InputMapper::reset(when);
4310}
4311
Michael Wright842500e2015-03-13 17:32:02 -07004312void TouchInputMapper::resetExternalStylus() {
4313 mExternalStylusState.clear();
4314 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004315 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004316 mExternalStylusDataPending = false;
4317}
4318
Michael Wright43fd19f2015-04-21 19:02:58 +01004319void TouchInputMapper::clearStylusDataPendingFlags() {
4320 mExternalStylusDataPending = false;
4321 mExternalStylusFusionTimeout = LLONG_MAX;
4322}
4323
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004324void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4325 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4326 nsecs_t latency = now - evdevTime;
4327 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4328 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4329 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4330 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
Siarhei Vishniakou05247bb2019-03-22 17:11:21 -07004331 mStatistics.min, mStatistics.max,
4332 mStatistics.mean(), mStatistics.stdev(), mStatistics.count);
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004333 mStatistics.reset(now);
4334 }
4335}
4336
Michael Wrightd02c5b62014-02-10 15:10:22 -08004337void TouchInputMapper::process(const RawEvent* rawEvent) {
4338 mCursorButtonAccumulator.process(rawEvent);
4339 mCursorScrollAccumulator.process(rawEvent);
4340 mTouchButtonAccumulator.process(rawEvent);
4341
4342 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004343 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 sync(rawEvent->when);
4345 }
4346}
4347
4348void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004349 const RawState* last = mRawStatesPending.empty() ?
4350 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004351
4352 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004353 mRawStatesPending.emplace_back();
4354
4355 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004356 next->clear();
4357 next->when = when;
4358
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004360 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361 | mCursorButtonAccumulator.getButtonState();
4362
Michael Wright842500e2015-03-13 17:32:02 -07004363 // Sync scroll
4364 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4365 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366 mCursorScrollAccumulator.finishSync();
4367
Michael Wright842500e2015-03-13 17:32:02 -07004368 // Sync touch
4369 syncTouch(when, next);
4370
4371 // Assign pointer ids.
4372 if (!mHavePointerIds) {
4373 assignPointerIds(last, next);
4374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
4376#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004377 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4378 "hovering ids 0x%08x -> 0x%08x",
4379 last->rawPointerData.pointerCount,
4380 next->rawPointerData.pointerCount,
4381 last->rawPointerData.touchingIdBits.value,
4382 next->rawPointerData.touchingIdBits.value,
4383 last->rawPointerData.hoveringIdBits.value,
4384 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004385#endif
4386
Michael Wright842500e2015-03-13 17:32:02 -07004387 processRawTouches(false /*timeout*/);
4388}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004389
Michael Wright842500e2015-03-13 17:32:02 -07004390void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004391 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4392 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004393 mCurrentRawState.clear();
4394 mRawStatesPending.clear();
4395 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004396 }
4397
Michael Wright842500e2015-03-13 17:32:02 -07004398 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4399 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4400 // touching the current state will only observe the events that have been dispatched to the
4401 // rest of the pipeline.
4402 const size_t N = mRawStatesPending.size();
4403 size_t count;
4404 for(count = 0; count < N; count++) {
4405 const RawState& next = mRawStatesPending[count];
4406
4407 // A failure to assign the stylus id means that we're waiting on stylus data
4408 // and so should defer the rest of the pipeline.
4409 if (assignExternalStylusId(next, timeout)) {
4410 break;
4411 }
4412
4413 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004414 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004415 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004416 if (mCurrentRawState.when < mLastRawState.when) {
4417 mCurrentRawState.when = mLastRawState.when;
4418 }
Michael Wright842500e2015-03-13 17:32:02 -07004419 cookAndDispatch(mCurrentRawState.when);
4420 }
4421 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004422 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004423 }
4424
Michael Wright842500e2015-03-13 17:32:02 -07004425 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004426 if (timeout) {
4427 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4428 clearStylusDataPendingFlags();
4429 mCurrentRawState.copyFrom(mLastRawState);
4430#if DEBUG_STYLUS_FUSION
4431 ALOGD("Timeout expired, synthesizing event with new stylus data");
4432#endif
4433 cookAndDispatch(when);
4434 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4435 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4436 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4437 }
Michael Wright842500e2015-03-13 17:32:02 -07004438 }
4439}
4440
4441void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4442 // Always start with a clean state.
4443 mCurrentCookedState.clear();
4444
4445 // Apply stylus buttons to current raw state.
4446 applyExternalStylusButtonState(when);
4447
4448 // Handle policy on initial down or hover events.
4449 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4450 && mCurrentRawState.rawPointerData.pointerCount != 0;
4451
4452 uint32_t policyFlags = 0;
4453 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4454 if (initialDown || buttonsPressed) {
4455 // If this is a touch screen, hide the pointer on an initial down.
4456 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4457 getContext()->fadePointer();
4458 }
4459
4460 if (mParameters.wake) {
4461 policyFlags |= POLICY_FLAG_WAKE;
4462 }
4463 }
4464
4465 // Consume raw off-screen touches before cooking pointer data.
4466 // If touches are consumed, subsequent code will not receive any pointer data.
4467 if (consumeRawTouches(when, policyFlags)) {
4468 mCurrentRawState.rawPointerData.clear();
4469 }
4470
4471 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4472 // with cooked pointer data that has the same ids and indices as the raw data.
4473 // The following code can use either the raw or cooked data, as needed.
4474 cookPointerData();
4475
4476 // Apply stylus pressure to current cooked state.
4477 applyExternalStylusTouchState(when);
4478
4479 // Synthesize key down from raw buttons if needed.
4480 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004481 mViewport.displayId, policyFlags,
4482 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004483
4484 // Dispatch the touches either directly or by translation through a pointer on screen.
4485 if (mDeviceMode == DEVICE_MODE_POINTER) {
4486 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4487 !idBits.isEmpty(); ) {
4488 uint32_t id = idBits.clearFirstMarkedBit();
4489 const RawPointerData::Pointer& pointer =
4490 mCurrentRawState.rawPointerData.pointerForId(id);
4491 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4492 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4493 mCurrentCookedState.stylusIdBits.markBit(id);
4494 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4495 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4496 mCurrentCookedState.fingerIdBits.markBit(id);
4497 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4498 mCurrentCookedState.mouseIdBits.markBit(id);
4499 }
4500 }
4501 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4502 !idBits.isEmpty(); ) {
4503 uint32_t id = idBits.clearFirstMarkedBit();
4504 const RawPointerData::Pointer& pointer =
4505 mCurrentRawState.rawPointerData.pointerForId(id);
4506 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4507 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4508 mCurrentCookedState.stylusIdBits.markBit(id);
4509 }
4510 }
4511
4512 // Stylus takes precedence over all tools, then mouse, then finger.
4513 PointerUsage pointerUsage = mPointerUsage;
4514 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4515 mCurrentCookedState.mouseIdBits.clear();
4516 mCurrentCookedState.fingerIdBits.clear();
4517 pointerUsage = POINTER_USAGE_STYLUS;
4518 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4519 mCurrentCookedState.fingerIdBits.clear();
4520 pointerUsage = POINTER_USAGE_MOUSE;
4521 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4522 isPointerDown(mCurrentRawState.buttonState)) {
4523 pointerUsage = POINTER_USAGE_GESTURES;
4524 }
4525
4526 dispatchPointerUsage(when, policyFlags, pointerUsage);
4527 } else {
4528 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004529 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004530 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4531 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4532
4533 mPointerController->setButtonState(mCurrentRawState.buttonState);
4534 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4535 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004536 mCurrentCookedState.cookedPointerData.touchingIdBits,
4537 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004538 }
4539
Michael Wright8e812822015-06-22 16:18:21 +01004540 if (!mCurrentMotionAborted) {
4541 dispatchButtonRelease(when, policyFlags);
4542 dispatchHoverExit(when, policyFlags);
4543 dispatchTouches(when, policyFlags);
4544 dispatchHoverEnterAndMove(when, policyFlags);
4545 dispatchButtonPress(when, policyFlags);
4546 }
4547
4548 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4549 mCurrentMotionAborted = false;
4550 }
Michael Wright842500e2015-03-13 17:32:02 -07004551 }
4552
4553 // Synthesize key up from raw buttons if needed.
4554 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004555 mViewport.displayId, policyFlags,
4556 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004557
4558 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004559 mCurrentRawState.rawVScroll = 0;
4560 mCurrentRawState.rawHScroll = 0;
4561
4562 // Copy current touch to last touch in preparation for the next cycle.
4563 mLastRawState.copyFrom(mCurrentRawState);
4564 mLastCookedState.copyFrom(mCurrentCookedState);
4565}
4566
4567void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004568 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004569 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4570 }
4571}
4572
4573void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004574 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4575 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004576
Michael Wright53dca3a2015-04-23 17:39:53 +01004577 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4578 float pressure = mExternalStylusState.pressure;
4579 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4580 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4581 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4582 }
4583 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4584 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4585
4586 PointerProperties& properties =
4587 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004588 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4589 properties.toolType = mExternalStylusState.toolType;
4590 }
4591 }
4592}
4593
4594bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4595 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4596 return false;
4597 }
4598
4599 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4600 && state.rawPointerData.pointerCount != 0;
4601 if (initialDown) {
4602 if (mExternalStylusState.pressure != 0.0f) {
4603#if DEBUG_STYLUS_FUSION
4604 ALOGD("Have both stylus and touch data, beginning fusion");
4605#endif
4606 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4607 } else if (timeout) {
4608#if DEBUG_STYLUS_FUSION
4609 ALOGD("Timeout expired, assuming touch is not a stylus.");
4610#endif
4611 resetExternalStylus();
4612 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004613 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4614 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004615 }
4616#if DEBUG_STYLUS_FUSION
4617 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004618 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004619#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004620 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004621 return true;
4622 }
4623 }
4624
4625 // Check if the stylus pointer has gone up.
4626 if (mExternalStylusId != -1 &&
4627 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4628#if DEBUG_STYLUS_FUSION
4629 ALOGD("Stylus pointer is going up");
4630#endif
4631 mExternalStylusId = -1;
4632 }
4633
4634 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004635}
4636
4637void TouchInputMapper::timeoutExpired(nsecs_t when) {
4638 if (mDeviceMode == DEVICE_MODE_POINTER) {
4639 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4640 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4641 }
Michael Wright842500e2015-03-13 17:32:02 -07004642 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004643 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004644 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004645 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4646 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004647 }
4648 }
4649}
4650
4651void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004652 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004653 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004654 // We're either in the middle of a fused stream of data or we're waiting on data before
4655 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4656 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004657 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004658 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 }
4660}
4661
4662bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4663 // Check for release of a virtual key.
4664 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004665 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004666 // Pointer went up while virtual key was down.
4667 mCurrentVirtualKey.down = false;
4668 if (!mCurrentVirtualKey.ignored) {
4669#if DEBUG_VIRTUAL_KEYS
4670 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4671 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4672#endif
4673 dispatchVirtualKey(when, policyFlags,
4674 AKEY_EVENT_ACTION_UP,
4675 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4676 }
4677 return true;
4678 }
4679
Michael Wright842500e2015-03-13 17:32:02 -07004680 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4681 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4682 const RawPointerData::Pointer& pointer =
4683 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4685 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4686 // Pointer is still within the space of the virtual key.
4687 return true;
4688 }
4689 }
4690
4691 // Pointer left virtual key area or another pointer also went down.
4692 // Send key cancellation but do not consume the touch yet.
4693 // This is useful when the user swipes through from the virtual key area
4694 // into the main display surface.
4695 mCurrentVirtualKey.down = false;
4696 if (!mCurrentVirtualKey.ignored) {
4697#if DEBUG_VIRTUAL_KEYS
4698 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4699 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4700#endif
4701 dispatchVirtualKey(when, policyFlags,
4702 AKEY_EVENT_ACTION_UP,
4703 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4704 | AKEY_EVENT_FLAG_CANCELED);
4705 }
4706 }
4707
Michael Wright842500e2015-03-13 17:32:02 -07004708 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4709 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004711 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4712 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004713 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4714 // If exactly one pointer went down, check for virtual key hit.
4715 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004716 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004717 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4718 if (virtualKey) {
4719 mCurrentVirtualKey.down = true;
4720 mCurrentVirtualKey.downTime = when;
4721 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4722 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4723 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4724 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4725
4726 if (!mCurrentVirtualKey.ignored) {
4727#if DEBUG_VIRTUAL_KEYS
4728 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4729 mCurrentVirtualKey.keyCode,
4730 mCurrentVirtualKey.scanCode);
4731#endif
4732 dispatchVirtualKey(when, policyFlags,
4733 AKEY_EVENT_ACTION_DOWN,
4734 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4735 }
4736 }
4737 }
4738 return true;
4739 }
4740 }
4741
4742 // Disable all virtual key touches that happen within a short time interval of the
4743 // most recent touch within the screen area. The idea is to filter out stray
4744 // virtual key presses when interacting with the touch screen.
4745 //
4746 // Problems we're trying to solve:
4747 //
4748 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4749 // virtual key area that is implemented by a separate touch panel and accidentally
4750 // triggers a virtual key.
4751 //
4752 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4753 // area and accidentally triggers a virtual key. This often happens when virtual keys
4754 // are layed out below the screen near to where the on screen keyboard's space bar
4755 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004756 if (mConfig.virtualKeyQuietTime > 0 &&
4757 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4759 }
4760 return false;
4761}
4762
4763void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4764 int32_t keyEventAction, int32_t keyEventFlags) {
4765 int32_t keyCode = mCurrentVirtualKey.keyCode;
4766 int32_t scanCode = mCurrentVirtualKey.scanCode;
4767 nsecs_t downTime = mCurrentVirtualKey.downTime;
4768 int32_t metaState = mContext->getGlobalMetaState();
4769 policyFlags |= POLICY_FLAG_VIRTUAL;
4770
Prabir Pradhan42611e02018-11-27 14:04:02 -08004771 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4772 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004773 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 getListener()->notifyKey(&args);
4775}
4776
Michael Wright8e812822015-06-22 16:18:21 +01004777void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4778 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4779 if (!currentIdBits.isEmpty()) {
4780 int32_t metaState = getContext()->getGlobalMetaState();
4781 int32_t buttonState = mCurrentCookedState.buttonState;
4782 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4783 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004784 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004785 mCurrentCookedState.cookedPointerData.pointerProperties,
4786 mCurrentCookedState.cookedPointerData.pointerCoords,
4787 mCurrentCookedState.cookedPointerData.idToIndex,
4788 currentIdBits, -1,
4789 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4790 mCurrentMotionAborted = true;
4791 }
4792}
4793
Michael Wrightd02c5b62014-02-10 15:10:22 -08004794void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004795 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4796 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004798 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799
4800 if (currentIdBits == lastIdBits) {
4801 if (!currentIdBits.isEmpty()) {
4802 // No pointer id changes so this is a move event.
4803 // The listener takes care of batching moves so we don't have to deal with that here.
4804 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004805 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004807 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004808 mCurrentCookedState.cookedPointerData.pointerProperties,
4809 mCurrentCookedState.cookedPointerData.pointerCoords,
4810 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811 currentIdBits, -1,
4812 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4813 }
4814 } else {
4815 // There may be pointers going up and pointers going down and pointers moving
4816 // all at the same time.
4817 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4818 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4819 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4820 BitSet32 dispatchedIdBits(lastIdBits.value);
4821
4822 // Update last coordinates of pointers that have moved so that we observe the new
4823 // pointer positions at the same time as other pointers that have just gone up.
4824 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004825 mCurrentCookedState.cookedPointerData.pointerProperties,
4826 mCurrentCookedState.cookedPointerData.pointerCoords,
4827 mCurrentCookedState.cookedPointerData.idToIndex,
4828 mLastCookedState.cookedPointerData.pointerProperties,
4829 mLastCookedState.cookedPointerData.pointerCoords,
4830 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004832 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 moveNeeded = true;
4834 }
4835
4836 // Dispatch pointer up events.
4837 while (!upIdBits.isEmpty()) {
4838 uint32_t upId = upIdBits.clearFirstMarkedBit();
4839
4840 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004841 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004842 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004843 mLastCookedState.cookedPointerData.pointerProperties,
4844 mLastCookedState.cookedPointerData.pointerCoords,
4845 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004846 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 dispatchedIdBits.clearBit(upId);
4848 }
4849
4850 // Dispatch move events if any of the remaining pointers moved from their old locations.
4851 // Although applications receive new locations as part of individual pointer up
4852 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004853 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4855 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004856 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004857 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004858 mCurrentCookedState.cookedPointerData.pointerProperties,
4859 mCurrentCookedState.cookedPointerData.pointerCoords,
4860 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004861 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004862 }
4863
4864 // Dispatch pointer down events using the new pointer locations.
4865 while (!downIdBits.isEmpty()) {
4866 uint32_t downId = downIdBits.clearFirstMarkedBit();
4867 dispatchedIdBits.markBit(downId);
4868
4869 if (dispatchedIdBits.count() == 1) {
4870 // First pointer is going down. Set down time.
4871 mDownTime = when;
4872 }
4873
4874 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004875 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004876 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004877 mCurrentCookedState.cookedPointerData.pointerProperties,
4878 mCurrentCookedState.cookedPointerData.pointerCoords,
4879 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004880 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 }
4882 }
4883}
4884
4885void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4886 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004887 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4888 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004889 int32_t metaState = getContext()->getGlobalMetaState();
4890 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004891 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004892 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004893 mLastCookedState.cookedPointerData.pointerProperties,
4894 mLastCookedState.cookedPointerData.pointerCoords,
4895 mLastCookedState.cookedPointerData.idToIndex,
4896 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4898 mSentHoverEnter = false;
4899 }
4900}
4901
4902void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004903 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4904 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 int32_t metaState = getContext()->getGlobalMetaState();
4906 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004907 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004908 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004909 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004910 mCurrentCookedState.cookedPointerData.pointerProperties,
4911 mCurrentCookedState.cookedPointerData.pointerCoords,
4912 mCurrentCookedState.cookedPointerData.idToIndex,
4913 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4915 mSentHoverEnter = true;
4916 }
4917
4918 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004919 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004920 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004921 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004922 mCurrentCookedState.cookedPointerData.pointerProperties,
4923 mCurrentCookedState.cookedPointerData.pointerCoords,
4924 mCurrentCookedState.cookedPointerData.idToIndex,
4925 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4927 }
4928}
4929
Michael Wright7b159c92015-05-14 14:48:03 +01004930void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4931 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4932 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4933 const int32_t metaState = getContext()->getGlobalMetaState();
4934 int32_t buttonState = mLastCookedState.buttonState;
4935 while (!releasedButtons.isEmpty()) {
4936 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4937 buttonState &= ~actionButton;
4938 dispatchMotion(when, policyFlags, mSource,
4939 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4940 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004941 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004942 mCurrentCookedState.cookedPointerData.pointerProperties,
4943 mCurrentCookedState.cookedPointerData.pointerCoords,
4944 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4945 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4946 }
4947}
4948
4949void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4950 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4951 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4952 const int32_t metaState = getContext()->getGlobalMetaState();
4953 int32_t buttonState = mLastCookedState.buttonState;
4954 while (!pressedButtons.isEmpty()) {
4955 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4956 buttonState |= actionButton;
4957 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4958 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004959 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004960 mCurrentCookedState.cookedPointerData.pointerProperties,
4961 mCurrentCookedState.cookedPointerData.pointerCoords,
4962 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4963 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4964 }
4965}
4966
4967const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4968 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4969 return cookedPointerData.touchingIdBits;
4970 }
4971 return cookedPointerData.hoveringIdBits;
4972}
4973
Michael Wrightd02c5b62014-02-10 15:10:22 -08004974void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004975 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
Michael Wright842500e2015-03-13 17:32:02 -07004977 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004978 mCurrentCookedState.deviceTimestamp =
4979 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004980 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4981 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4982 mCurrentRawState.rawPointerData.hoveringIdBits;
4983 mCurrentCookedState.cookedPointerData.touchingIdBits =
4984 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004985
Michael Wright7b159c92015-05-14 14:48:03 +01004986 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4987 mCurrentCookedState.buttonState = 0;
4988 } else {
4989 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4990 }
4991
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992 // Walk through the the active pointers and map device coordinates onto
4993 // surface coordinates and adjust for display orientation.
4994 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004995 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004996
4997 // Size
4998 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4999 switch (mCalibration.sizeCalibration) {
5000 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
5001 case Calibration::SIZE_CALIBRATION_DIAMETER:
5002 case Calibration::SIZE_CALIBRATION_BOX:
5003 case Calibration::SIZE_CALIBRATION_AREA:
5004 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
5005 touchMajor = in.touchMajor;
5006 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
5007 toolMajor = in.toolMajor;
5008 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
5009 size = mRawPointerAxes.touchMinor.valid
5010 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5011 } else if (mRawPointerAxes.touchMajor.valid) {
5012 toolMajor = touchMajor = in.touchMajor;
5013 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
5014 ? in.touchMinor : in.touchMajor;
5015 size = mRawPointerAxes.touchMinor.valid
5016 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5017 } else if (mRawPointerAxes.toolMajor.valid) {
5018 touchMajor = toolMajor = in.toolMajor;
5019 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5020 ? in.toolMinor : in.toolMajor;
5021 size = mRawPointerAxes.toolMinor.valid
5022 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5023 } else {
5024 ALOG_ASSERT(false, "No touch or tool axes. "
5025 "Size calibration should have been resolved to NONE.");
5026 touchMajor = 0;
5027 touchMinor = 0;
5028 toolMajor = 0;
5029 toolMinor = 0;
5030 size = 0;
5031 }
5032
5033 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005034 uint32_t touchingCount =
5035 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005036 if (touchingCount > 1) {
5037 touchMajor /= touchingCount;
5038 touchMinor /= touchingCount;
5039 toolMajor /= touchingCount;
5040 toolMinor /= touchingCount;
5041 size /= touchingCount;
5042 }
5043 }
5044
5045 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5046 touchMajor *= mGeometricScale;
5047 touchMinor *= mGeometricScale;
5048 toolMajor *= mGeometricScale;
5049 toolMinor *= mGeometricScale;
5050 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5051 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5052 touchMinor = touchMajor;
5053 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5054 toolMinor = toolMajor;
5055 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5056 touchMinor = touchMajor;
5057 toolMinor = toolMajor;
5058 }
5059
5060 mCalibration.applySizeScaleAndBias(&touchMajor);
5061 mCalibration.applySizeScaleAndBias(&touchMinor);
5062 mCalibration.applySizeScaleAndBias(&toolMajor);
5063 mCalibration.applySizeScaleAndBias(&toolMinor);
5064 size *= mSizeScale;
5065 break;
5066 default:
5067 touchMajor = 0;
5068 touchMinor = 0;
5069 toolMajor = 0;
5070 toolMinor = 0;
5071 size = 0;
5072 break;
5073 }
5074
5075 // Pressure
5076 float pressure;
5077 switch (mCalibration.pressureCalibration) {
5078 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5079 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5080 pressure = in.pressure * mPressureScale;
5081 break;
5082 default:
5083 pressure = in.isHovering ? 0 : 1;
5084 break;
5085 }
5086
5087 // Tilt and Orientation
5088 float tilt;
5089 float orientation;
5090 if (mHaveTilt) {
5091 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5092 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5093 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5094 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5095 } else {
5096 tilt = 0;
5097
5098 switch (mCalibration.orientationCalibration) {
5099 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5100 orientation = in.orientation * mOrientationScale;
5101 break;
5102 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5103 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5104 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5105 if (c1 != 0 || c2 != 0) {
5106 orientation = atan2f(c1, c2) * 0.5f;
5107 float confidence = hypotf(c1, c2);
5108 float scale = 1.0f + confidence / 16.0f;
5109 touchMajor *= scale;
5110 touchMinor /= scale;
5111 toolMajor *= scale;
5112 toolMinor /= scale;
5113 } else {
5114 orientation = 0;
5115 }
5116 break;
5117 }
5118 default:
5119 orientation = 0;
5120 }
5121 }
5122
5123 // Distance
5124 float distance;
5125 switch (mCalibration.distanceCalibration) {
5126 case Calibration::DISTANCE_CALIBRATION_SCALED:
5127 distance = in.distance * mDistanceScale;
5128 break;
5129 default:
5130 distance = 0;
5131 }
5132
5133 // Coverage
5134 int32_t rawLeft, rawTop, rawRight, rawBottom;
5135 switch (mCalibration.coverageCalibration) {
5136 case Calibration::COVERAGE_CALIBRATION_BOX:
5137 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5138 rawRight = in.toolMinor & 0x0000ffff;
5139 rawBottom = in.toolMajor & 0x0000ffff;
5140 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5141 break;
5142 default:
5143 rawLeft = rawTop = rawRight = rawBottom = 0;
5144 break;
5145 }
5146
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005147 // Adjust X,Y coords for device calibration
5148 // TODO: Adjust coverage coords?
5149 float xTransformed = in.x, yTransformed = in.y;
5150 mAffineTransform.applyTo(xTransformed, yTransformed);
5151
5152 // Adjust X, Y, and coverage coords for surface orientation.
5153 float x, y;
5154 float left, top, right, bottom;
5155
Michael Wrightd02c5b62014-02-10 15:10:22 -08005156 switch (mSurfaceOrientation) {
5157 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005158 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5159 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5161 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5162 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5163 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5164 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005165 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5167 }
5168 break;
5169 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005170 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005171 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005172 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5173 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5175 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5176 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005177 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5179 }
5180 break;
5181 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005182 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005183 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005184 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5185 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5187 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5188 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005189 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5191 }
5192 break;
5193 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005194 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5195 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5197 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5198 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5199 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5200 break;
5201 }
5202
5203 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005204 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005205 out.clear();
5206 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5207 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5208 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5209 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5210 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5211 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5212 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5213 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5214 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5215 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5216 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5217 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5218 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5219 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5220 } else {
5221 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5222 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5223 }
5224
5225 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005226 PointerProperties& properties =
5227 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228 uint32_t id = in.id;
5229 properties.clear();
5230 properties.id = id;
5231 properties.toolType = in.toolType;
5232
5233 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005234 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005235 }
5236}
5237
5238void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5239 PointerUsage pointerUsage) {
5240 if (pointerUsage != mPointerUsage) {
5241 abortPointerUsage(when, policyFlags);
5242 mPointerUsage = pointerUsage;
5243 }
5244
5245 switch (mPointerUsage) {
5246 case POINTER_USAGE_GESTURES:
5247 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5248 break;
5249 case POINTER_USAGE_STYLUS:
5250 dispatchPointerStylus(when, policyFlags);
5251 break;
5252 case POINTER_USAGE_MOUSE:
5253 dispatchPointerMouse(when, policyFlags);
5254 break;
5255 default:
5256 break;
5257 }
5258}
5259
5260void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5261 switch (mPointerUsage) {
5262 case POINTER_USAGE_GESTURES:
5263 abortPointerGestures(when, policyFlags);
5264 break;
5265 case POINTER_USAGE_STYLUS:
5266 abortPointerStylus(when, policyFlags);
5267 break;
5268 case POINTER_USAGE_MOUSE:
5269 abortPointerMouse(when, policyFlags);
5270 break;
5271 default:
5272 break;
5273 }
5274
5275 mPointerUsage = POINTER_USAGE_NONE;
5276}
5277
5278void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5279 bool isTimeout) {
5280 // Update current gesture coordinates.
5281 bool cancelPreviousGesture, finishPreviousGesture;
5282 bool sendEvents = preparePointerGestures(when,
5283 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5284 if (!sendEvents) {
5285 return;
5286 }
5287 if (finishPreviousGesture) {
5288 cancelPreviousGesture = false;
5289 }
5290
5291 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005292 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5293 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 if (finishPreviousGesture || cancelPreviousGesture) {
5295 mPointerController->clearSpots();
5296 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005297
5298 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5299 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5300 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005301 mPointerGesture.currentGestureIdBits,
5302 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005303 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 } else {
5305 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5306 }
5307
5308 // Show or hide the pointer if needed.
5309 switch (mPointerGesture.currentGestureMode) {
5310 case PointerGesture::NEUTRAL:
5311 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005312 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5313 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 // Remind the user of where the pointer is after finishing a gesture with spots.
5315 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5316 }
5317 break;
5318 case PointerGesture::TAP:
5319 case PointerGesture::TAP_DRAG:
5320 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5321 case PointerGesture::HOVER:
5322 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005323 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005324 // Unfade the pointer when the current gesture manipulates the
5325 // area directly under the pointer.
5326 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5327 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328 case PointerGesture::FREEFORM:
5329 // Fade the pointer when the current gesture manipulates a different
5330 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005331 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005332 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5333 } else {
5334 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5335 }
5336 break;
5337 }
5338
5339 // Send events!
5340 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005341 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342
5343 // Update last coordinates of pointers that have moved so that we observe the new
5344 // pointer positions at the same time as other pointers that have just gone up.
5345 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5346 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5347 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5348 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5349 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5350 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5351 bool moveNeeded = false;
5352 if (down && !cancelPreviousGesture && !finishPreviousGesture
5353 && !mPointerGesture.lastGestureIdBits.isEmpty()
5354 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5355 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5356 & mPointerGesture.lastGestureIdBits.value);
5357 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5358 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5359 mPointerGesture.lastGestureProperties,
5360 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5361 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005362 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 moveNeeded = true;
5364 }
5365 }
5366
5367 // Send motion events for all pointers that went up or were canceled.
5368 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5369 if (!dispatchedGestureIdBits.isEmpty()) {
5370 if (cancelPreviousGesture) {
5371 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005372 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005373 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 mPointerGesture.lastGestureProperties,
5375 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005376 dispatchedGestureIdBits, -1, 0,
5377 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378
5379 dispatchedGestureIdBits.clear();
5380 } else {
5381 BitSet32 upGestureIdBits;
5382 if (finishPreviousGesture) {
5383 upGestureIdBits = dispatchedGestureIdBits;
5384 } else {
5385 upGestureIdBits.value = dispatchedGestureIdBits.value
5386 & ~mPointerGesture.currentGestureIdBits.value;
5387 }
5388 while (!upGestureIdBits.isEmpty()) {
5389 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5390
5391 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005392 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005394 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 mPointerGesture.lastGestureProperties,
5396 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5397 dispatchedGestureIdBits, id,
5398 0, 0, mPointerGesture.downTime);
5399
5400 dispatchedGestureIdBits.clearBit(id);
5401 }
5402 }
5403 }
5404
5405 // Send motion events for all pointers that moved.
5406 if (moveNeeded) {
5407 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005408 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005409 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 mPointerGesture.currentGestureProperties,
5411 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5412 dispatchedGestureIdBits, -1,
5413 0, 0, mPointerGesture.downTime);
5414 }
5415
5416 // Send motion events for all pointers that went down.
5417 if (down) {
5418 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5419 & ~dispatchedGestureIdBits.value);
5420 while (!downGestureIdBits.isEmpty()) {
5421 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5422 dispatchedGestureIdBits.markBit(id);
5423
5424 if (dispatchedGestureIdBits.count() == 1) {
5425 mPointerGesture.downTime = when;
5426 }
5427
5428 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005429 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005430 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005431 mPointerGesture.currentGestureProperties,
5432 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5433 dispatchedGestureIdBits, id,
5434 0, 0, mPointerGesture.downTime);
5435 }
5436 }
5437
5438 // Send motion events for hover.
5439 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5440 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005441 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005442 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005443 mPointerGesture.currentGestureProperties,
5444 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5445 mPointerGesture.currentGestureIdBits, -1,
5446 0, 0, mPointerGesture.downTime);
5447 } else if (dispatchedGestureIdBits.isEmpty()
5448 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5449 // Synthesize a hover move event after all pointers go up to indicate that
5450 // the pointer is hovering again even if the user is not currently touching
5451 // the touch pad. This ensures that a view will receive a fresh hover enter
5452 // event after a tap.
5453 float x, y;
5454 mPointerController->getPosition(&x, &y);
5455
5456 PointerProperties pointerProperties;
5457 pointerProperties.clear();
5458 pointerProperties.id = 0;
5459 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5460
5461 PointerCoords pointerCoords;
5462 pointerCoords.clear();
5463 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5464 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5465
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005466 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005467 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5468 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5469 metaState, buttonState, MotionClassification::NONE,
5470 AMOTION_EVENT_EDGE_FLAG_NONE,
5471 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0,
5472 x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005473 getListener()->notifyMotion(&args);
5474 }
5475
5476 // Update state.
5477 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5478 if (!down) {
5479 mPointerGesture.lastGestureIdBits.clear();
5480 } else {
5481 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5482 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5483 uint32_t id = idBits.clearFirstMarkedBit();
5484 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5485 mPointerGesture.lastGestureProperties[index].copyFrom(
5486 mPointerGesture.currentGestureProperties[index]);
5487 mPointerGesture.lastGestureCoords[index].copyFrom(
5488 mPointerGesture.currentGestureCoords[index]);
5489 mPointerGesture.lastGestureIdToIndex[id] = index;
5490 }
5491 }
5492}
5493
5494void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5495 // Cancel previously dispatches pointers.
5496 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5497 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005498 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005500 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005501 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005502 mPointerGesture.lastGestureProperties,
5503 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5504 mPointerGesture.lastGestureIdBits, -1,
5505 0, 0, mPointerGesture.downTime);
5506 }
5507
5508 // Reset the current pointer gesture.
5509 mPointerGesture.reset();
5510 mPointerVelocityControl.reset();
5511
5512 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005513 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5515 mPointerController->clearSpots();
5516 }
5517}
5518
5519bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5520 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5521 *outCancelPreviousGesture = false;
5522 *outFinishPreviousGesture = false;
5523
5524 // Handle TAP timeout.
5525 if (isTimeout) {
5526#if DEBUG_GESTURES
5527 ALOGD("Gestures: Processing timeout");
5528#endif
5529
5530 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5531 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5532 // The tap/drag timeout has not yet expired.
5533 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5534 + mConfig.pointerGestureTapDragInterval);
5535 } else {
5536 // The tap is finished.
5537#if DEBUG_GESTURES
5538 ALOGD("Gestures: TAP finished");
5539#endif
5540 *outFinishPreviousGesture = true;
5541
5542 mPointerGesture.activeGestureId = -1;
5543 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5544 mPointerGesture.currentGestureIdBits.clear();
5545
5546 mPointerVelocityControl.reset();
5547 return true;
5548 }
5549 }
5550
5551 // We did not handle this timeout.
5552 return false;
5553 }
5554
Michael Wright842500e2015-03-13 17:32:02 -07005555 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5556 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557
5558 // Update the velocity tracker.
5559 {
5560 VelocityTracker::Position positions[MAX_POINTERS];
5561 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005562 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005564 const RawPointerData::Pointer& pointer =
5565 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 positions[count].x = pointer.x * mPointerXMovementScale;
5567 positions[count].y = pointer.y * mPointerYMovementScale;
5568 }
5569 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005570 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 }
5572
5573 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5574 // to NEUTRAL, then we should not generate tap event.
5575 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5576 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5577 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5578 mPointerGesture.resetTap();
5579 }
5580
5581 // Pick a new active touch id if needed.
5582 // Choose an arbitrary pointer that just went down, if there is one.
5583 // Otherwise choose an arbitrary remaining pointer.
5584 // This guarantees we always have an active touch id when there is at least one pointer.
5585 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5587 int32_t activeTouchId = lastActiveTouchId;
5588 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005589 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005590 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005591 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592 mPointerGesture.firstTouchTime = when;
5593 }
Michael Wright842500e2015-03-13 17:32:02 -07005594 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005595 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005596 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005597 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 } else {
5599 activeTouchId = mPointerGesture.activeTouchId = -1;
5600 }
5601 }
5602
5603 // Determine whether we are in quiet time.
5604 bool isQuietTime = false;
5605 if (activeTouchId < 0) {
5606 mPointerGesture.resetQuietTime();
5607 } else {
5608 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5609 if (!isQuietTime) {
5610 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5611 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5612 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5613 && currentFingerCount < 2) {
5614 // Enter quiet time when exiting swipe or freeform state.
5615 // This is to prevent accidentally entering the hover state and flinging the
5616 // pointer when finishing a swipe and there is still one pointer left onscreen.
5617 isQuietTime = true;
5618 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5619 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005620 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 // Enter quiet time when releasing the button and there are still two or more
5622 // fingers down. This may indicate that one finger was used to press the button
5623 // but it has not gone up yet.
5624 isQuietTime = true;
5625 }
5626 if (isQuietTime) {
5627 mPointerGesture.quietTime = when;
5628 }
5629 }
5630 }
5631
5632 // Switch states based on button and pointer state.
5633 if (isQuietTime) {
5634 // Case 1: Quiet time. (QUIET)
5635#if DEBUG_GESTURES
5636 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5637 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5638#endif
5639 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5640 *outFinishPreviousGesture = true;
5641 }
5642
5643 mPointerGesture.activeGestureId = -1;
5644 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5645 mPointerGesture.currentGestureIdBits.clear();
5646
5647 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005648 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5650 // The pointer follows the active touch point.
5651 // Emit DOWN, MOVE, UP events at the pointer location.
5652 //
5653 // Only the active touch matters; other fingers are ignored. This policy helps
5654 // to handle the case where the user places a second finger on the touch pad
5655 // to apply the necessary force to depress an integrated button below the surface.
5656 // We don't want the second finger to be delivered to applications.
5657 //
5658 // For this to work well, we need to make sure to track the pointer that is really
5659 // active. If the user first puts one finger down to click then adds another
5660 // finger to drag then the active pointer should switch to the finger that is
5661 // being dragged.
5662#if DEBUG_GESTURES
5663 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5664 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5665#endif
5666 // Reset state when just starting.
5667 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5668 *outFinishPreviousGesture = true;
5669 mPointerGesture.activeGestureId = 0;
5670 }
5671
5672 // Switch pointers if needed.
5673 // Find the fastest pointer and follow it.
5674 if (activeTouchId >= 0 && currentFingerCount > 1) {
5675 int32_t bestId = -1;
5676 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005677 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 uint32_t id = idBits.clearFirstMarkedBit();
5679 float vx, vy;
5680 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5681 float speed = hypotf(vx, vy);
5682 if (speed > bestSpeed) {
5683 bestId = id;
5684 bestSpeed = speed;
5685 }
5686 }
5687 }
5688 if (bestId >= 0 && bestId != activeTouchId) {
5689 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690#if DEBUG_GESTURES
5691 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5692 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5693#endif
5694 }
5695 }
5696
Jun Mukaifa1706a2015-12-03 01:14:46 -08005697 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005698 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005699 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005700 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005701 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005702 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005703 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5704 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705
5706 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5707 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5708
5709 // Move the pointer using a relative motion.
5710 // When using spots, the click will occur at the position of the anchor
5711 // spot and all other spots will move there.
5712 mPointerController->move(deltaX, deltaY);
5713 } else {
5714 mPointerVelocityControl.reset();
5715 }
5716
5717 float x, y;
5718 mPointerController->getPosition(&x, &y);
5719
5720 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5721 mPointerGesture.currentGestureIdBits.clear();
5722 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5723 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5724 mPointerGesture.currentGestureProperties[0].clear();
5725 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5726 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5727 mPointerGesture.currentGestureCoords[0].clear();
5728 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5729 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5730 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5731 } else if (currentFingerCount == 0) {
5732 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5733 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5734 *outFinishPreviousGesture = true;
5735 }
5736
5737 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5738 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5739 bool tapped = false;
5740 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5741 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5742 && lastFingerCount == 1) {
5743 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5744 float x, y;
5745 mPointerController->getPosition(&x, &y);
5746 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5747 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5748#if DEBUG_GESTURES
5749 ALOGD("Gestures: TAP");
5750#endif
5751
5752 mPointerGesture.tapUpTime = when;
5753 getContext()->requestTimeoutAtTime(when
5754 + mConfig.pointerGestureTapDragInterval);
5755
5756 mPointerGesture.activeGestureId = 0;
5757 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5758 mPointerGesture.currentGestureIdBits.clear();
5759 mPointerGesture.currentGestureIdBits.markBit(
5760 mPointerGesture.activeGestureId);
5761 mPointerGesture.currentGestureIdToIndex[
5762 mPointerGesture.activeGestureId] = 0;
5763 mPointerGesture.currentGestureProperties[0].clear();
5764 mPointerGesture.currentGestureProperties[0].id =
5765 mPointerGesture.activeGestureId;
5766 mPointerGesture.currentGestureProperties[0].toolType =
5767 AMOTION_EVENT_TOOL_TYPE_FINGER;
5768 mPointerGesture.currentGestureCoords[0].clear();
5769 mPointerGesture.currentGestureCoords[0].setAxisValue(
5770 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5771 mPointerGesture.currentGestureCoords[0].setAxisValue(
5772 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5773 mPointerGesture.currentGestureCoords[0].setAxisValue(
5774 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5775
5776 tapped = true;
5777 } else {
5778#if DEBUG_GESTURES
5779 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5780 x - mPointerGesture.tapX,
5781 y - mPointerGesture.tapY);
5782#endif
5783 }
5784 } else {
5785#if DEBUG_GESTURES
5786 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5787 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5788 (when - mPointerGesture.tapDownTime) * 0.000001f);
5789 } else {
5790 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5791 }
5792#endif
5793 }
5794 }
5795
5796 mPointerVelocityControl.reset();
5797
5798 if (!tapped) {
5799#if DEBUG_GESTURES
5800 ALOGD("Gestures: NEUTRAL");
5801#endif
5802 mPointerGesture.activeGestureId = -1;
5803 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5804 mPointerGesture.currentGestureIdBits.clear();
5805 }
5806 } else if (currentFingerCount == 1) {
5807 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5808 // The pointer follows the active touch point.
5809 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5810 // When in TAP_DRAG, emit MOVE events at the pointer location.
5811 ALOG_ASSERT(activeTouchId >= 0);
5812
5813 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5814 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5815 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5816 float x, y;
5817 mPointerController->getPosition(&x, &y);
5818 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5819 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5820 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5821 } else {
5822#if DEBUG_GESTURES
5823 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5824 x - mPointerGesture.tapX,
5825 y - mPointerGesture.tapY);
5826#endif
5827 }
5828 } else {
5829#if DEBUG_GESTURES
5830 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5831 (when - mPointerGesture.tapUpTime) * 0.000001f);
5832#endif
5833 }
5834 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5835 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5836 }
5837
Jun Mukaifa1706a2015-12-03 01:14:46 -08005838 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005839 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005840 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005841 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005843 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005844 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5845 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005846
5847 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5848 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5849
5850 // Move the pointer using a relative motion.
5851 // When using spots, the hover or drag will occur at the position of the anchor spot.
5852 mPointerController->move(deltaX, deltaY);
5853 } else {
5854 mPointerVelocityControl.reset();
5855 }
5856
5857 bool down;
5858 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5859#if DEBUG_GESTURES
5860 ALOGD("Gestures: TAP_DRAG");
5861#endif
5862 down = true;
5863 } else {
5864#if DEBUG_GESTURES
5865 ALOGD("Gestures: HOVER");
5866#endif
5867 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5868 *outFinishPreviousGesture = true;
5869 }
5870 mPointerGesture.activeGestureId = 0;
5871 down = false;
5872 }
5873
5874 float x, y;
5875 mPointerController->getPosition(&x, &y);
5876
5877 mPointerGesture.currentGestureIdBits.clear();
5878 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5879 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5880 mPointerGesture.currentGestureProperties[0].clear();
5881 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5882 mPointerGesture.currentGestureProperties[0].toolType =
5883 AMOTION_EVENT_TOOL_TYPE_FINGER;
5884 mPointerGesture.currentGestureCoords[0].clear();
5885 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5886 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5887 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5888 down ? 1.0f : 0.0f);
5889
5890 if (lastFingerCount == 0 && currentFingerCount != 0) {
5891 mPointerGesture.resetTap();
5892 mPointerGesture.tapDownTime = when;
5893 mPointerGesture.tapX = x;
5894 mPointerGesture.tapY = y;
5895 }
5896 } else {
5897 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5898 // We need to provide feedback for each finger that goes down so we cannot wait
5899 // for the fingers to move before deciding what to do.
5900 //
5901 // The ambiguous case is deciding what to do when there are two fingers down but they
5902 // have not moved enough to determine whether they are part of a drag or part of a
5903 // freeform gesture, or just a press or long-press at the pointer location.
5904 //
5905 // When there are two fingers we start with the PRESS hypothesis and we generate a
5906 // down at the pointer location.
5907 //
5908 // When the two fingers move enough or when additional fingers are added, we make
5909 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5910 ALOG_ASSERT(activeTouchId >= 0);
5911
5912 bool settled = when >= mPointerGesture.firstTouchTime
5913 + mConfig.pointerGestureMultitouchSettleInterval;
5914 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5915 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5916 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5917 *outFinishPreviousGesture = true;
5918 } else if (!settled && currentFingerCount > lastFingerCount) {
5919 // Additional pointers have gone down but not yet settled.
5920 // Reset the gesture.
5921#if DEBUG_GESTURES
5922 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5923 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5924 + mConfig.pointerGestureMultitouchSettleInterval - when)
5925 * 0.000001f);
5926#endif
5927 *outCancelPreviousGesture = true;
5928 } else {
5929 // Continue previous gesture.
5930 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5931 }
5932
5933 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5934 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5935 mPointerGesture.activeGestureId = 0;
5936 mPointerGesture.referenceIdBits.clear();
5937 mPointerVelocityControl.reset();
5938
5939 // Use the centroid and pointer location as the reference points for the gesture.
5940#if DEBUG_GESTURES
5941 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5942 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5943 + mConfig.pointerGestureMultitouchSettleInterval - when)
5944 * 0.000001f);
5945#endif
Michael Wright842500e2015-03-13 17:32:02 -07005946 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 &mPointerGesture.referenceTouchX,
5948 &mPointerGesture.referenceTouchY);
5949 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5950 &mPointerGesture.referenceGestureY);
5951 }
5952
5953 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005954 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5956 uint32_t id = idBits.clearFirstMarkedBit();
5957 mPointerGesture.referenceDeltas[id].dx = 0;
5958 mPointerGesture.referenceDeltas[id].dy = 0;
5959 }
Michael Wright842500e2015-03-13 17:32:02 -07005960 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961
5962 // Add delta for all fingers and calculate a common movement delta.
5963 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005964 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5965 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005966 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5967 bool first = (idBits == commonIdBits);
5968 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005969 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5970 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005971 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5972 delta.dx += cpd.x - lpd.x;
5973 delta.dy += cpd.y - lpd.y;
5974
5975 if (first) {
5976 commonDeltaX = delta.dx;
5977 commonDeltaY = delta.dy;
5978 } else {
5979 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5980 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5981 }
5982 }
5983
5984 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5985 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5986 float dist[MAX_POINTER_ID + 1];
5987 int32_t distOverThreshold = 0;
5988 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5989 uint32_t id = idBits.clearFirstMarkedBit();
5990 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5991 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5992 delta.dy * mPointerYZoomScale);
5993 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5994 distOverThreshold += 1;
5995 }
5996 }
5997
5998 // Only transition when at least two pointers have moved further than
5999 // the minimum distance threshold.
6000 if (distOverThreshold >= 2) {
6001 if (currentFingerCount > 2) {
6002 // There are more than two pointers, switch to FREEFORM.
6003#if DEBUG_GESTURES
6004 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
6005 currentFingerCount);
6006#endif
6007 *outCancelPreviousGesture = true;
6008 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6009 } else {
6010 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07006011 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006012 uint32_t id1 = idBits.clearFirstMarkedBit();
6013 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07006014 const RawPointerData::Pointer& p1 =
6015 mCurrentRawState.rawPointerData.pointerForId(id1);
6016 const RawPointerData::Pointer& p2 =
6017 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006018 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6019 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6020 // There are two pointers but they are too far apart for a SWIPE,
6021 // switch to FREEFORM.
6022#if DEBUG_GESTURES
6023 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6024 mutualDistance, mPointerGestureMaxSwipeWidth);
6025#endif
6026 *outCancelPreviousGesture = true;
6027 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6028 } else {
6029 // There are two pointers. Wait for both pointers to start moving
6030 // before deciding whether this is a SWIPE or FREEFORM gesture.
6031 float dist1 = dist[id1];
6032 float dist2 = dist[id2];
6033 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6034 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6035 // Calculate the dot product of the displacement vectors.
6036 // When the vectors are oriented in approximately the same direction,
6037 // the angle betweeen them is near zero and the cosine of the angle
6038 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6039 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6040 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6041 float dx1 = delta1.dx * mPointerXZoomScale;
6042 float dy1 = delta1.dy * mPointerYZoomScale;
6043 float dx2 = delta2.dx * mPointerXZoomScale;
6044 float dy2 = delta2.dy * mPointerYZoomScale;
6045 float dot = dx1 * dx2 + dy1 * dy2;
6046 float cosine = dot / (dist1 * dist2); // denominator always > 0
6047 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6048 // Pointers are moving in the same direction. Switch to SWIPE.
6049#if DEBUG_GESTURES
6050 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6051 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6052 "cosine %0.3f >= %0.3f",
6053 dist1, mConfig.pointerGestureMultitouchMinDistance,
6054 dist2, mConfig.pointerGestureMultitouchMinDistance,
6055 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6056#endif
6057 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6058 } else {
6059 // Pointers are moving in different directions. Switch to FREEFORM.
6060#if DEBUG_GESTURES
6061 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6062 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6063 "cosine %0.3f < %0.3f",
6064 dist1, mConfig.pointerGestureMultitouchMinDistance,
6065 dist2, mConfig.pointerGestureMultitouchMinDistance,
6066 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6067#endif
6068 *outCancelPreviousGesture = true;
6069 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6070 }
6071 }
6072 }
6073 }
6074 }
6075 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6076 // Switch from SWIPE to FREEFORM if additional pointers go down.
6077 // Cancel previous gesture.
6078 if (currentFingerCount > 2) {
6079#if DEBUG_GESTURES
6080 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6081 currentFingerCount);
6082#endif
6083 *outCancelPreviousGesture = true;
6084 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6085 }
6086 }
6087
6088 // Move the reference points based on the overall group motion of the fingers
6089 // except in PRESS mode while waiting for a transition to occur.
6090 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6091 && (commonDeltaX || commonDeltaY)) {
6092 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6093 uint32_t id = idBits.clearFirstMarkedBit();
6094 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6095 delta.dx = 0;
6096 delta.dy = 0;
6097 }
6098
6099 mPointerGesture.referenceTouchX += commonDeltaX;
6100 mPointerGesture.referenceTouchY += commonDeltaY;
6101
6102 commonDeltaX *= mPointerXMovementScale;
6103 commonDeltaY *= mPointerYMovementScale;
6104
6105 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6106 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6107
6108 mPointerGesture.referenceGestureX += commonDeltaX;
6109 mPointerGesture.referenceGestureY += commonDeltaY;
6110 }
6111
6112 // Report gestures.
6113 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6114 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6115 // PRESS or SWIPE mode.
6116#if DEBUG_GESTURES
6117 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6118 "activeGestureId=%d, currentTouchPointerCount=%d",
6119 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6120#endif
6121 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6122
6123 mPointerGesture.currentGestureIdBits.clear();
6124 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6125 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6126 mPointerGesture.currentGestureProperties[0].clear();
6127 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6128 mPointerGesture.currentGestureProperties[0].toolType =
6129 AMOTION_EVENT_TOOL_TYPE_FINGER;
6130 mPointerGesture.currentGestureCoords[0].clear();
6131 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6132 mPointerGesture.referenceGestureX);
6133 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6134 mPointerGesture.referenceGestureY);
6135 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6136 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6137 // FREEFORM mode.
6138#if DEBUG_GESTURES
6139 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6140 "activeGestureId=%d, currentTouchPointerCount=%d",
6141 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6142#endif
6143 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6144
6145 mPointerGesture.currentGestureIdBits.clear();
6146
6147 BitSet32 mappedTouchIdBits;
6148 BitSet32 usedGestureIdBits;
6149 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6150 // Initially, assign the active gesture id to the active touch point
6151 // if there is one. No other touch id bits are mapped yet.
6152 if (!*outCancelPreviousGesture) {
6153 mappedTouchIdBits.markBit(activeTouchId);
6154 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6155 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6156 mPointerGesture.activeGestureId;
6157 } else {
6158 mPointerGesture.activeGestureId = -1;
6159 }
6160 } else {
6161 // Otherwise, assume we mapped all touches from the previous frame.
6162 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006163 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6164 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006165 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6166
6167 // Check whether we need to choose a new active gesture id because the
6168 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006169 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6170 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006171 !upTouchIdBits.isEmpty(); ) {
6172 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6173 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6174 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6175 mPointerGesture.activeGestureId = -1;
6176 break;
6177 }
6178 }
6179 }
6180
6181#if DEBUG_GESTURES
6182 ALOGD("Gestures: FREEFORM follow up "
6183 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6184 "activeGestureId=%d",
6185 mappedTouchIdBits.value, usedGestureIdBits.value,
6186 mPointerGesture.activeGestureId);
6187#endif
6188
Michael Wright842500e2015-03-13 17:32:02 -07006189 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190 for (uint32_t i = 0; i < currentFingerCount; i++) {
6191 uint32_t touchId = idBits.clearFirstMarkedBit();
6192 uint32_t gestureId;
6193 if (!mappedTouchIdBits.hasBit(touchId)) {
6194 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6195 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6196#if DEBUG_GESTURES
6197 ALOGD("Gestures: FREEFORM "
6198 "new mapping for touch id %d -> gesture id %d",
6199 touchId, gestureId);
6200#endif
6201 } else {
6202 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6203#if DEBUG_GESTURES
6204 ALOGD("Gestures: FREEFORM "
6205 "existing mapping for touch id %d -> gesture id %d",
6206 touchId, gestureId);
6207#endif
6208 }
6209 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6210 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6211
6212 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006213 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006214 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6215 * mPointerXZoomScale;
6216 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6217 * mPointerYZoomScale;
6218 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6219
6220 mPointerGesture.currentGestureProperties[i].clear();
6221 mPointerGesture.currentGestureProperties[i].id = gestureId;
6222 mPointerGesture.currentGestureProperties[i].toolType =
6223 AMOTION_EVENT_TOOL_TYPE_FINGER;
6224 mPointerGesture.currentGestureCoords[i].clear();
6225 mPointerGesture.currentGestureCoords[i].setAxisValue(
6226 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6227 mPointerGesture.currentGestureCoords[i].setAxisValue(
6228 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6229 mPointerGesture.currentGestureCoords[i].setAxisValue(
6230 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6231 }
6232
6233 if (mPointerGesture.activeGestureId < 0) {
6234 mPointerGesture.activeGestureId =
6235 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6236#if DEBUG_GESTURES
6237 ALOGD("Gestures: FREEFORM new "
6238 "activeGestureId=%d", mPointerGesture.activeGestureId);
6239#endif
6240 }
6241 }
6242 }
6243
Michael Wright842500e2015-03-13 17:32:02 -07006244 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006245
6246#if DEBUG_GESTURES
6247 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6248 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6249 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6250 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6251 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6252 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6253 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6254 uint32_t id = idBits.clearFirstMarkedBit();
6255 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6256 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6257 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6258 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6259 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6260 id, index, properties.toolType,
6261 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6262 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6263 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6264 }
6265 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6266 uint32_t id = idBits.clearFirstMarkedBit();
6267 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6268 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6269 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6270 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6271 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6272 id, index, properties.toolType,
6273 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6274 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6275 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6276 }
6277#endif
6278 return true;
6279}
6280
6281void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6282 mPointerSimple.currentCoords.clear();
6283 mPointerSimple.currentProperties.clear();
6284
6285 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006286 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6287 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6288 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6289 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6290 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291 mPointerController->setPosition(x, y);
6292
Michael Wright842500e2015-03-13 17:32:02 -07006293 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006294 down = !hovering;
6295
6296 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006297 mPointerSimple.currentCoords.copyFrom(
6298 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6300 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6301 mPointerSimple.currentProperties.id = 0;
6302 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006303 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006304 } else {
6305 down = false;
6306 hovering = false;
6307 }
6308
6309 dispatchPointerSimple(when, policyFlags, down, hovering);
6310}
6311
6312void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6313 abortPointerSimple(when, policyFlags);
6314}
6315
6316void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6317 mPointerSimple.currentCoords.clear();
6318 mPointerSimple.currentProperties.clear();
6319
6320 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006321 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6322 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6323 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006324 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006325 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6326 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006327 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006328 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006330 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006331 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 * mPointerYMovementScale;
6333
6334 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6335 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6336
6337 mPointerController->move(deltaX, deltaY);
6338 } else {
6339 mPointerVelocityControl.reset();
6340 }
6341
Michael Wright842500e2015-03-13 17:32:02 -07006342 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006343 hovering = !down;
6344
6345 float x, y;
6346 mPointerController->getPosition(&x, &y);
6347 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006348 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6350 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6351 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6352 hovering ? 0.0f : 1.0f);
6353 mPointerSimple.currentProperties.id = 0;
6354 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006355 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006356 } else {
6357 mPointerVelocityControl.reset();
6358
6359 down = false;
6360 hovering = false;
6361 }
6362
6363 dispatchPointerSimple(when, policyFlags, down, hovering);
6364}
6365
6366void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6367 abortPointerSimple(when, policyFlags);
6368
6369 mPointerVelocityControl.reset();
6370}
6371
6372void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6373 bool down, bool hovering) {
6374 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006375 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376
Garfield Tan00f511d2019-06-12 16:55:40 -07006377 if (down || hovering) {
6378 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6379 mPointerController->clearSpots();
6380 mPointerController->setButtonState(mCurrentRawState.buttonState);
6381 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6382 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6383 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006384 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006385 displayId = mPointerController->getDisplayId();
6386
6387 float xCursorPosition;
6388 float yCursorPosition;
6389 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006390
6391 if (mPointerSimple.down && !down) {
6392 mPointerSimple.down = false;
6393
6394 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006395 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6396 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6397 mLastRawState.buttonState, MotionClassification::NONE,
6398 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6399 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6400 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6401 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 getListener()->notifyMotion(&args);
6403 }
6404
6405 if (mPointerSimple.hovering && !hovering) {
6406 mPointerSimple.hovering = false;
6407
6408 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006409 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6410 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6411 metaState, mLastRawState.buttonState, MotionClassification::NONE,
6412 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6413 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6414 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6415 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 getListener()->notifyMotion(&args);
6417 }
6418
6419 if (down) {
6420 if (!mPointerSimple.down) {
6421 mPointerSimple.down = true;
6422 mPointerSimple.downTime = when;
6423
6424 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006425 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6426 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6427 metaState, mCurrentRawState.buttonState,
6428 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
6429 /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties,
6430 &mPointerSimple.currentCoords, mOrientedXPrecision,
6431 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6432 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006433 getListener()->notifyMotion(&args);
6434 }
6435
6436 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006437 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6438 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6439 mCurrentRawState.buttonState, MotionClassification::NONE,
6440 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6441 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6442 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6443 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006444 getListener()->notifyMotion(&args);
6445 }
6446
6447 if (hovering) {
6448 if (!mPointerSimple.hovering) {
6449 mPointerSimple.hovering = true;
6450
6451 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006452 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6453 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6454 metaState, mCurrentRawState.buttonState,
6455 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
6456 /* deviceTimestamp */ 0, 1, &mPointerSimple.currentProperties,
6457 &mPointerSimple.currentCoords, mOrientedXPrecision,
6458 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6459 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006460 getListener()->notifyMotion(&args);
6461 }
6462
6463 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006464 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6465 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6466 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
6467 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6468 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6469 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6470 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006471 getListener()->notifyMotion(&args);
6472 }
6473
Michael Wright842500e2015-03-13 17:32:02 -07006474 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6475 float vscroll = mCurrentRawState.rawVScroll;
6476 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006477 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6478 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006479
6480 // Send scroll.
6481 PointerCoords pointerCoords;
6482 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6483 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6484 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6485
Garfield Tan00f511d2019-06-12 16:55:40 -07006486 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6487 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6488 mCurrentRawState.buttonState, MotionClassification::NONE,
6489 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
6490 &mPointerSimple.currentProperties, &pointerCoords,
6491 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6492 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493 getListener()->notifyMotion(&args);
6494 }
6495
6496 // Save state.
6497 if (down || hovering) {
6498 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6499 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6500 } else {
6501 mPointerSimple.reset();
6502 }
6503}
6504
6505void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6506 mPointerSimple.currentCoords.clear();
6507 mPointerSimple.currentProperties.clear();
6508
6509 dispatchPointerSimple(when, policyFlags, false, false);
6510}
6511
6512void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006513 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006514 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006515 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006516 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6517 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518 PointerCoords pointerCoords[MAX_POINTERS];
6519 PointerProperties pointerProperties[MAX_POINTERS];
6520 uint32_t pointerCount = 0;
6521 while (!idBits.isEmpty()) {
6522 uint32_t id = idBits.clearFirstMarkedBit();
6523 uint32_t index = idToIndex[id];
6524 pointerProperties[pointerCount].copyFrom(properties[index]);
6525 pointerCoords[pointerCount].copyFrom(coords[index]);
6526
6527 if (changedId >= 0 && id == uint32_t(changedId)) {
6528 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6529 }
6530
6531 pointerCount += 1;
6532 }
6533
6534 ALOG_ASSERT(pointerCount != 0);
6535
6536 if (changedId >= 0 && pointerCount == 1) {
6537 // Replace initial down and final up action.
6538 // We can compare the action without masking off the changed pointer index
6539 // because we know the index is 0.
6540 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6541 action = AMOTION_EVENT_ACTION_DOWN;
6542 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6543 action = AMOTION_EVENT_ACTION_UP;
6544 } else {
6545 // Can't happen.
6546 ALOG_ASSERT(false);
6547 }
6548 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006549 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6550 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6551 if (mDeviceMode == DEVICE_MODE_POINTER) {
6552 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6553 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006554 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006555 const int32_t deviceId = getDeviceId();
6556 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006557 std::for_each(frames.begin(), frames.end(),
6558 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006559 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6560 policyFlags, action, actionButton, flags, metaState, buttonState,
6561 MotionClassification::NONE, edgeFlags, deviceTimestamp, pointerCount,
6562 pointerProperties, pointerCoords, xPrecision, yPrecision, xCursorPosition,
6563 yCursorPosition, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 getListener()->notifyMotion(&args);
6565}
6566
6567bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6568 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6569 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6570 BitSet32 idBits) const {
6571 bool changed = false;
6572 while (!idBits.isEmpty()) {
6573 uint32_t id = idBits.clearFirstMarkedBit();
6574 uint32_t inIndex = inIdToIndex[id];
6575 uint32_t outIndex = outIdToIndex[id];
6576
6577 const PointerProperties& curInProperties = inProperties[inIndex];
6578 const PointerCoords& curInCoords = inCoords[inIndex];
6579 PointerProperties& curOutProperties = outProperties[outIndex];
6580 PointerCoords& curOutCoords = outCoords[outIndex];
6581
6582 if (curInProperties != curOutProperties) {
6583 curOutProperties.copyFrom(curInProperties);
6584 changed = true;
6585 }
6586
6587 if (curInCoords != curOutCoords) {
6588 curOutCoords.copyFrom(curInCoords);
6589 changed = true;
6590 }
6591 }
6592 return changed;
6593}
6594
6595void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006596 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6598 }
6599}
6600
Jeff Brownc9aa6282015-02-11 19:03:28 -08006601void TouchInputMapper::cancelTouch(nsecs_t when) {
6602 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006603 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006604}
6605
Michael Wrightd02c5b62014-02-10 15:10:22 -08006606bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006607 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006608 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006610 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6611 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6612 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613}
6614
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006615const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006617 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618#if DEBUG_VIRTUAL_KEYS
6619 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6620 "left=%d, top=%d, right=%d, bottom=%d",
6621 x, y,
6622 virtualKey.keyCode, virtualKey.scanCode,
6623 virtualKey.hitLeft, virtualKey.hitTop,
6624 virtualKey.hitRight, virtualKey.hitBottom);
6625#endif
6626
6627 if (virtualKey.isHit(x, y)) {
6628 return & virtualKey;
6629 }
6630 }
6631
Yi Kong9b14ac62018-07-17 13:48:38 -07006632 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006633}
6634
Michael Wright842500e2015-03-13 17:32:02 -07006635void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6636 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6637 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006638
Michael Wright842500e2015-03-13 17:32:02 -07006639 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640
6641 if (currentPointerCount == 0) {
6642 // No pointers to assign.
6643 return;
6644 }
6645
6646 if (lastPointerCount == 0) {
6647 // All pointers are new.
6648 for (uint32_t i = 0; i < currentPointerCount; i++) {
6649 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006650 current->rawPointerData.pointers[i].id = id;
6651 current->rawPointerData.idToIndex[id] = i;
6652 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006653 }
6654 return;
6655 }
6656
6657 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006658 && current->rawPointerData.pointers[0].toolType
6659 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006660 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006661 uint32_t id = last->rawPointerData.pointers[0].id;
6662 current->rawPointerData.pointers[0].id = id;
6663 current->rawPointerData.idToIndex[id] = 0;
6664 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006665 return;
6666 }
6667
6668 // General case.
6669 // We build a heap of squared euclidean distances between current and last pointers
6670 // associated with the current and last pointer indices. Then, we find the best
6671 // match (by distance) for each current pointer.
6672 // The pointers must have the same tool type but it is possible for them to
6673 // transition from hovering to touching or vice-versa while retaining the same id.
6674 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6675
6676 uint32_t heapSize = 0;
6677 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6678 currentPointerIndex++) {
6679 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6680 lastPointerIndex++) {
6681 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006682 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006683 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006684 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006685 if (currentPointer.toolType == lastPointer.toolType) {
6686 int64_t deltaX = currentPointer.x - lastPointer.x;
6687 int64_t deltaY = currentPointer.y - lastPointer.y;
6688
6689 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6690
6691 // Insert new element into the heap (sift up).
6692 heap[heapSize].currentPointerIndex = currentPointerIndex;
6693 heap[heapSize].lastPointerIndex = lastPointerIndex;
6694 heap[heapSize].distance = distance;
6695 heapSize += 1;
6696 }
6697 }
6698 }
6699
6700 // Heapify
6701 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6702 startIndex -= 1;
6703 for (uint32_t parentIndex = startIndex; ;) {
6704 uint32_t childIndex = parentIndex * 2 + 1;
6705 if (childIndex >= heapSize) {
6706 break;
6707 }
6708
6709 if (childIndex + 1 < heapSize
6710 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6711 childIndex += 1;
6712 }
6713
6714 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6715 break;
6716 }
6717
6718 swap(heap[parentIndex], heap[childIndex]);
6719 parentIndex = childIndex;
6720 }
6721 }
6722
6723#if DEBUG_POINTER_ASSIGNMENT
6724 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6725 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006726 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006727 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6728 heap[i].distance);
6729 }
6730#endif
6731
6732 // Pull matches out by increasing order of distance.
6733 // To avoid reassigning pointers that have already been matched, the loop keeps track
6734 // of which last and current pointers have been matched using the matchedXXXBits variables.
6735 // It also tracks the used pointer id bits.
6736 BitSet32 matchedLastBits(0);
6737 BitSet32 matchedCurrentBits(0);
6738 BitSet32 usedIdBits(0);
6739 bool first = true;
6740 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6741 while (heapSize > 0) {
6742 if (first) {
6743 // The first time through the loop, we just consume the root element of
6744 // the heap (the one with smallest distance).
6745 first = false;
6746 } else {
6747 // Previous iterations consumed the root element of the heap.
6748 // Pop root element off of the heap (sift down).
6749 heap[0] = heap[heapSize];
6750 for (uint32_t parentIndex = 0; ;) {
6751 uint32_t childIndex = parentIndex * 2 + 1;
6752 if (childIndex >= heapSize) {
6753 break;
6754 }
6755
6756 if (childIndex + 1 < heapSize
6757 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6758 childIndex += 1;
6759 }
6760
6761 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6762 break;
6763 }
6764
6765 swap(heap[parentIndex], heap[childIndex]);
6766 parentIndex = childIndex;
6767 }
6768
6769#if DEBUG_POINTER_ASSIGNMENT
6770 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6771 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006772 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006773 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6774 heap[i].distance);
6775 }
6776#endif
6777 }
6778
6779 heapSize -= 1;
6780
6781 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6782 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6783
6784 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6785 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6786
6787 matchedCurrentBits.markBit(currentPointerIndex);
6788 matchedLastBits.markBit(lastPointerIndex);
6789
Michael Wright842500e2015-03-13 17:32:02 -07006790 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6791 current->rawPointerData.pointers[currentPointerIndex].id = id;
6792 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6793 current->rawPointerData.markIdBit(id,
6794 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006795 usedIdBits.markBit(id);
6796
6797#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006798 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6799 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006800 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6801#endif
6802 break;
6803 }
6804 }
6805
6806 // Assign fresh ids to pointers that were not matched in the process.
6807 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6808 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6809 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6810
Michael Wright842500e2015-03-13 17:32:02 -07006811 current->rawPointerData.pointers[currentPointerIndex].id = id;
6812 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6813 current->rawPointerData.markIdBit(id,
6814 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006815
6816#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006817 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006818#endif
6819 }
6820}
6821
6822int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6823 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6824 return AKEY_STATE_VIRTUAL;
6825 }
6826
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006827 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006828 if (virtualKey.keyCode == keyCode) {
6829 return AKEY_STATE_UP;
6830 }
6831 }
6832
6833 return AKEY_STATE_UNKNOWN;
6834}
6835
6836int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6837 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6838 return AKEY_STATE_VIRTUAL;
6839 }
6840
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006841 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006842 if (virtualKey.scanCode == scanCode) {
6843 return AKEY_STATE_UP;
6844 }
6845 }
6846
6847 return AKEY_STATE_UNKNOWN;
6848}
6849
6850bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6851 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006852 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006853 for (size_t i = 0; i < numCodes; i++) {
6854 if (virtualKey.keyCode == keyCodes[i]) {
6855 outFlags[i] = 1;
6856 }
6857 }
6858 }
6859
6860 return true;
6861}
6862
Arthur Hungc23540e2018-11-29 20:42:11 +08006863std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6864 if (mParameters.hasAssociatedDisplay) {
6865 if (mDeviceMode == DEVICE_MODE_POINTER) {
6866 return std::make_optional(mPointerController->getDisplayId());
6867 } else {
6868 return std::make_optional(mViewport.displayId);
6869 }
6870 }
6871 return std::nullopt;
6872}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006873
6874// --- SingleTouchInputMapper ---
6875
6876SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6877 TouchInputMapper(device) {
6878}
6879
6880SingleTouchInputMapper::~SingleTouchInputMapper() {
6881}
6882
6883void SingleTouchInputMapper::reset(nsecs_t when) {
6884 mSingleTouchMotionAccumulator.reset(getDevice());
6885
6886 TouchInputMapper::reset(when);
6887}
6888
6889void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6890 TouchInputMapper::process(rawEvent);
6891
6892 mSingleTouchMotionAccumulator.process(rawEvent);
6893}
6894
Michael Wright842500e2015-03-13 17:32:02 -07006895void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006896 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006897 outState->rawPointerData.pointerCount = 1;
6898 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006899
6900 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6901 && (mTouchButtonAccumulator.isHovering()
6902 || (mRawPointerAxes.pressure.valid
6903 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006904 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006905
Michael Wright842500e2015-03-13 17:32:02 -07006906 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006907 outPointer.id = 0;
6908 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6909 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6910 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6911 outPointer.touchMajor = 0;
6912 outPointer.touchMinor = 0;
6913 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6914 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6915 outPointer.orientation = 0;
6916 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6917 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6918 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6919 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6920 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6921 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6922 }
6923 outPointer.isHovering = isHovering;
6924 }
6925}
6926
6927void SingleTouchInputMapper::configureRawPointerAxes() {
6928 TouchInputMapper::configureRawPointerAxes();
6929
6930 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6931 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6932 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6933 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6934 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6935 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6936 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6937}
6938
6939bool SingleTouchInputMapper::hasStylus() const {
6940 return mTouchButtonAccumulator.hasStylus();
6941}
6942
6943
6944// --- MultiTouchInputMapper ---
6945
6946MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6947 TouchInputMapper(device) {
6948}
6949
6950MultiTouchInputMapper::~MultiTouchInputMapper() {
6951}
6952
6953void MultiTouchInputMapper::reset(nsecs_t when) {
6954 mMultiTouchMotionAccumulator.reset(getDevice());
6955
6956 mPointerIdBits.clear();
6957
6958 TouchInputMapper::reset(when);
6959}
6960
6961void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6962 TouchInputMapper::process(rawEvent);
6963
6964 mMultiTouchMotionAccumulator.process(rawEvent);
6965}
6966
Michael Wright842500e2015-03-13 17:32:02 -07006967void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006968 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6969 size_t outCount = 0;
6970 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006971 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006972
6973 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6974 const MultiTouchMotionAccumulator::Slot* inSlot =
6975 mMultiTouchMotionAccumulator.getSlot(inIndex);
6976 if (!inSlot->isInUse()) {
6977 continue;
6978 }
6979
6980 if (outCount >= MAX_POINTERS) {
6981#if DEBUG_POINTERS
6982 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6983 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006984 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006985#endif
6986 break; // too many fingers!
6987 }
6988
Michael Wright842500e2015-03-13 17:32:02 -07006989 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006990 outPointer.x = inSlot->getX();
6991 outPointer.y = inSlot->getY();
6992 outPointer.pressure = inSlot->getPressure();
6993 outPointer.touchMajor = inSlot->getTouchMajor();
6994 outPointer.touchMinor = inSlot->getTouchMinor();
6995 outPointer.toolMajor = inSlot->getToolMajor();
6996 outPointer.toolMinor = inSlot->getToolMinor();
6997 outPointer.orientation = inSlot->getOrientation();
6998 outPointer.distance = inSlot->getDistance();
6999 outPointer.tiltX = 0;
7000 outPointer.tiltY = 0;
7001
7002 outPointer.toolType = inSlot->getToolType();
7003 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7004 outPointer.toolType = mTouchButtonAccumulator.getToolType();
7005 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7006 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
7007 }
7008 }
7009
7010 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
7011 && (mTouchButtonAccumulator.isHovering()
7012 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
7013 outPointer.isHovering = isHovering;
7014
7015 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08007016 if (mHavePointerIds) {
7017 int32_t trackingId = inSlot->getTrackingId();
7018 int32_t id = -1;
7019 if (trackingId >= 0) {
7020 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7021 uint32_t n = idBits.clearFirstMarkedBit();
7022 if (mPointerTrackingIdMap[n] == trackingId) {
7023 id = n;
7024 }
7025 }
7026
7027 if (id < 0 && !mPointerIdBits.isFull()) {
7028 id = mPointerIdBits.markFirstUnmarkedBit();
7029 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007030 }
Michael Wright842500e2015-03-13 17:32:02 -07007031 }
gaoshang1a632de2016-08-24 10:23:50 +08007032 if (id < 0) {
7033 mHavePointerIds = false;
7034 outState->rawPointerData.clearIdBits();
7035 newPointerIdBits.clear();
7036 } else {
7037 outPointer.id = id;
7038 outState->rawPointerData.idToIndex[id] = outCount;
7039 outState->rawPointerData.markIdBit(id, isHovering);
7040 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007041 }
Michael Wright842500e2015-03-13 17:32:02 -07007042 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007043 outCount += 1;
7044 }
7045
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007046 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007047 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007048 mPointerIdBits = newPointerIdBits;
7049
7050 mMultiTouchMotionAccumulator.finishSync();
7051}
7052
7053void MultiTouchInputMapper::configureRawPointerAxes() {
7054 TouchInputMapper::configureRawPointerAxes();
7055
7056 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7057 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7058 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7059 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7060 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7061 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7062 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7063 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7064 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7065 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7066 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7067
7068 if (mRawPointerAxes.trackingId.valid
7069 && mRawPointerAxes.slot.valid
7070 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7071 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7072 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007073 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7074 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007075 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007076 slotCount = MAX_SLOTS;
7077 }
7078 mMultiTouchMotionAccumulator.configure(getDevice(),
7079 slotCount, true /*usingSlotsProtocol*/);
7080 } else {
7081 mMultiTouchMotionAccumulator.configure(getDevice(),
7082 MAX_POINTERS, false /*usingSlotsProtocol*/);
7083 }
7084}
7085
7086bool MultiTouchInputMapper::hasStylus() const {
7087 return mMultiTouchMotionAccumulator.hasStylus()
7088 || mTouchButtonAccumulator.hasStylus();
7089}
7090
Michael Wright842500e2015-03-13 17:32:02 -07007091// --- ExternalStylusInputMapper
7092
7093ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7094 InputMapper(device) {
7095
7096}
7097
7098uint32_t ExternalStylusInputMapper::getSources() {
7099 return AINPUT_SOURCE_STYLUS;
7100}
7101
7102void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7103 InputMapper::populateDeviceInfo(info);
7104 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7105 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7106}
7107
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007108void ExternalStylusInputMapper::dump(std::string& dump) {
7109 dump += INDENT2 "External Stylus Input Mapper:\n";
7110 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007111 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007112 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007113 dumpStylusState(dump, mStylusState);
7114}
7115
7116void ExternalStylusInputMapper::configure(nsecs_t when,
7117 const InputReaderConfiguration* config, uint32_t changes) {
7118 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7119 mTouchButtonAccumulator.configure(getDevice());
7120}
7121
7122void ExternalStylusInputMapper::reset(nsecs_t when) {
7123 InputDevice* device = getDevice();
7124 mSingleTouchMotionAccumulator.reset(device);
7125 mTouchButtonAccumulator.reset(device);
7126 InputMapper::reset(when);
7127}
7128
7129void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7130 mSingleTouchMotionAccumulator.process(rawEvent);
7131 mTouchButtonAccumulator.process(rawEvent);
7132
7133 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7134 sync(rawEvent->when);
7135 }
7136}
7137
7138void ExternalStylusInputMapper::sync(nsecs_t when) {
7139 mStylusState.clear();
7140
7141 mStylusState.when = when;
7142
Michael Wright45ccacf2015-04-21 19:01:58 +01007143 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7144 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7145 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7146 }
7147
Michael Wright842500e2015-03-13 17:32:02 -07007148 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7149 if (mRawPressureAxis.valid) {
7150 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7151 } else if (mTouchButtonAccumulator.isToolActive()) {
7152 mStylusState.pressure = 1.0f;
7153 } else {
7154 mStylusState.pressure = 0.0f;
7155 }
7156
7157 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007158
7159 mContext->dispatchExternalStylusState(mStylusState);
7160}
7161
Michael Wrightd02c5b62014-02-10 15:10:22 -08007162
7163// --- JoystickInputMapper ---
7164
7165JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7166 InputMapper(device) {
7167}
7168
7169JoystickInputMapper::~JoystickInputMapper() {
7170}
7171
7172uint32_t JoystickInputMapper::getSources() {
7173 return AINPUT_SOURCE_JOYSTICK;
7174}
7175
7176void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7177 InputMapper::populateDeviceInfo(info);
7178
7179 for (size_t i = 0; i < mAxes.size(); i++) {
7180 const Axis& axis = mAxes.valueAt(i);
7181 addMotionRange(axis.axisInfo.axis, axis, info);
7182
7183 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7184 addMotionRange(axis.axisInfo.highAxis, axis, info);
7185
7186 }
7187 }
7188}
7189
7190void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7191 InputDeviceInfo* info) {
7192 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7193 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7194 /* In order to ease the transition for developers from using the old axes
7195 * to the newer, more semantically correct axes, we'll continue to register
7196 * the old axes as duplicates of their corresponding new ones. */
7197 int32_t compatAxis = getCompatAxis(axisId);
7198 if (compatAxis >= 0) {
7199 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7200 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7201 }
7202}
7203
7204/* A mapping from axes the joystick actually has to the axes that should be
7205 * artificially created for compatibility purposes.
7206 * Returns -1 if no compatibility axis is needed. */
7207int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7208 switch(axis) {
7209 case AMOTION_EVENT_AXIS_LTRIGGER:
7210 return AMOTION_EVENT_AXIS_BRAKE;
7211 case AMOTION_EVENT_AXIS_RTRIGGER:
7212 return AMOTION_EVENT_AXIS_GAS;
7213 }
7214 return -1;
7215}
7216
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007217void JoystickInputMapper::dump(std::string& dump) {
7218 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007219
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007220 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007221 size_t numAxes = mAxes.size();
7222 for (size_t i = 0; i < numAxes; i++) {
7223 const Axis& axis = mAxes.valueAt(i);
7224 const char* label = getAxisLabel(axis.axisInfo.axis);
7225 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007226 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007227 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007228 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007229 }
7230 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7231 label = getAxisLabel(axis.axisInfo.highAxis);
7232 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007233 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007234 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007235 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007236 axis.axisInfo.splitValue);
7237 }
7238 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007239 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007240 }
7241
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007242 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 -08007243 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007244 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007245 "highScale=%0.5f, highOffset=%0.5f\n",
7246 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007247 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007248 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7249 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7250 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7251 }
7252}
7253
7254void JoystickInputMapper::configure(nsecs_t when,
7255 const InputReaderConfiguration* config, uint32_t changes) {
7256 InputMapper::configure(when, config, changes);
7257
7258 if (!changes) { // first time only
7259 // Collect all axes.
7260 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7261 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7262 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7263 continue; // axis must be claimed by a different device
7264 }
7265
7266 RawAbsoluteAxisInfo rawAxisInfo;
7267 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7268 if (rawAxisInfo.valid) {
7269 // Map axis.
7270 AxisInfo axisInfo;
7271 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7272 if (!explicitlyMapped) {
7273 // Axis is not explicitly mapped, will choose a generic axis later.
7274 axisInfo.mode = AxisInfo::MODE_NORMAL;
7275 axisInfo.axis = -1;
7276 }
7277
7278 // Apply flat override.
7279 int32_t rawFlat = axisInfo.flatOverride < 0
7280 ? rawAxisInfo.flat : axisInfo.flatOverride;
7281
7282 // Calculate scaling factors and limits.
7283 Axis axis;
7284 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7285 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7286 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7287 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7288 scale, 0.0f, highScale, 0.0f,
7289 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7290 rawAxisInfo.resolution * scale);
7291 } else if (isCenteredAxis(axisInfo.axis)) {
7292 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7293 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7294 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7295 scale, offset, scale, offset,
7296 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7297 rawAxisInfo.resolution * scale);
7298 } else {
7299 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7300 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7301 scale, 0.0f, scale, 0.0f,
7302 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7303 rawAxisInfo.resolution * scale);
7304 }
7305
7306 // To eliminate noise while the joystick is at rest, filter out small variations
7307 // in axis values up front.
7308 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7309
7310 mAxes.add(abs, axis);
7311 }
7312 }
7313
7314 // If there are too many axes, start dropping them.
7315 // Prefer to keep explicitly mapped axes.
7316 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007317 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007318 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007319 pruneAxes(true);
7320 pruneAxes(false);
7321 }
7322
7323 // Assign generic axis ids to remaining axes.
7324 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7325 size_t numAxes = mAxes.size();
7326 for (size_t i = 0; i < numAxes; i++) {
7327 Axis& axis = mAxes.editValueAt(i);
7328 if (axis.axisInfo.axis < 0) {
7329 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7330 && haveAxis(nextGenericAxisId)) {
7331 nextGenericAxisId += 1;
7332 }
7333
7334 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7335 axis.axisInfo.axis = nextGenericAxisId;
7336 nextGenericAxisId += 1;
7337 } else {
7338 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7339 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007340 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007341 mAxes.removeItemsAt(i--);
7342 numAxes -= 1;
7343 }
7344 }
7345 }
7346 }
7347}
7348
7349bool JoystickInputMapper::haveAxis(int32_t axisId) {
7350 size_t numAxes = mAxes.size();
7351 for (size_t i = 0; i < numAxes; i++) {
7352 const Axis& axis = mAxes.valueAt(i);
7353 if (axis.axisInfo.axis == axisId
7354 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7355 && axis.axisInfo.highAxis == axisId)) {
7356 return true;
7357 }
7358 }
7359 return false;
7360}
7361
7362void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7363 size_t i = mAxes.size();
7364 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7365 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7366 continue;
7367 }
7368 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007369 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007370 mAxes.removeItemsAt(i);
7371 }
7372}
7373
7374bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7375 switch (axis) {
7376 case AMOTION_EVENT_AXIS_X:
7377 case AMOTION_EVENT_AXIS_Y:
7378 case AMOTION_EVENT_AXIS_Z:
7379 case AMOTION_EVENT_AXIS_RX:
7380 case AMOTION_EVENT_AXIS_RY:
7381 case AMOTION_EVENT_AXIS_RZ:
7382 case AMOTION_EVENT_AXIS_HAT_X:
7383 case AMOTION_EVENT_AXIS_HAT_Y:
7384 case AMOTION_EVENT_AXIS_ORIENTATION:
7385 case AMOTION_EVENT_AXIS_RUDDER:
7386 case AMOTION_EVENT_AXIS_WHEEL:
7387 return true;
7388 default:
7389 return false;
7390 }
7391}
7392
7393void JoystickInputMapper::reset(nsecs_t when) {
7394 // Recenter all axes.
7395 size_t numAxes = mAxes.size();
7396 for (size_t i = 0; i < numAxes; i++) {
7397 Axis& axis = mAxes.editValueAt(i);
7398 axis.resetValue();
7399 }
7400
7401 InputMapper::reset(when);
7402}
7403
7404void JoystickInputMapper::process(const RawEvent* rawEvent) {
7405 switch (rawEvent->type) {
7406 case EV_ABS: {
7407 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7408 if (index >= 0) {
7409 Axis& axis = mAxes.editValueAt(index);
7410 float newValue, highNewValue;
7411 switch (axis.axisInfo.mode) {
7412 case AxisInfo::MODE_INVERT:
7413 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7414 * axis.scale + axis.offset;
7415 highNewValue = 0.0f;
7416 break;
7417 case AxisInfo::MODE_SPLIT:
7418 if (rawEvent->value < axis.axisInfo.splitValue) {
7419 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7420 * axis.scale + axis.offset;
7421 highNewValue = 0.0f;
7422 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7423 newValue = 0.0f;
7424 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7425 * axis.highScale + axis.highOffset;
7426 } else {
7427 newValue = 0.0f;
7428 highNewValue = 0.0f;
7429 }
7430 break;
7431 default:
7432 newValue = rawEvent->value * axis.scale + axis.offset;
7433 highNewValue = 0.0f;
7434 break;
7435 }
7436 axis.newValue = newValue;
7437 axis.highNewValue = highNewValue;
7438 }
7439 break;
7440 }
7441
7442 case EV_SYN:
7443 switch (rawEvent->code) {
7444 case SYN_REPORT:
7445 sync(rawEvent->when, false /*force*/);
7446 break;
7447 }
7448 break;
7449 }
7450}
7451
7452void JoystickInputMapper::sync(nsecs_t when, bool force) {
7453 if (!filterAxes(force)) {
7454 return;
7455 }
7456
7457 int32_t metaState = mContext->getGlobalMetaState();
7458 int32_t buttonState = 0;
7459
7460 PointerProperties pointerProperties;
7461 pointerProperties.clear();
7462 pointerProperties.id = 0;
7463 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7464
7465 PointerCoords pointerCoords;
7466 pointerCoords.clear();
7467
7468 size_t numAxes = mAxes.size();
7469 for (size_t i = 0; i < numAxes; i++) {
7470 const Axis& axis = mAxes.valueAt(i);
7471 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7472 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7473 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7474 axis.highCurrentValue);
7475 }
7476 }
7477
7478 // Moving a joystick axis should not wake the device because joysticks can
7479 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7480 // button will likely wake the device.
7481 // TODO: Use the input device configuration to control this behavior more finely.
7482 uint32_t policyFlags = 0;
7483
Prabir Pradhan42611e02018-11-27 14:04:02 -08007484 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007485 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7486 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
7487 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
7488 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords, 0, 0,
7489 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7490 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007491 getListener()->notifyMotion(&args);
7492}
7493
7494void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7495 int32_t axis, float value) {
7496 pointerCoords->setAxisValue(axis, value);
7497 /* In order to ease the transition for developers from using the old axes
7498 * to the newer, more semantically correct axes, we'll continue to produce
7499 * values for the old axes as mirrors of the value of their corresponding
7500 * new axes. */
7501 int32_t compatAxis = getCompatAxis(axis);
7502 if (compatAxis >= 0) {
7503 pointerCoords->setAxisValue(compatAxis, value);
7504 }
7505}
7506
7507bool JoystickInputMapper::filterAxes(bool force) {
7508 bool atLeastOneSignificantChange = force;
7509 size_t numAxes = mAxes.size();
7510 for (size_t i = 0; i < numAxes; i++) {
7511 Axis& axis = mAxes.editValueAt(i);
7512 if (force || hasValueChangedSignificantly(axis.filter,
7513 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7514 axis.currentValue = axis.newValue;
7515 atLeastOneSignificantChange = true;
7516 }
7517 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7518 if (force || hasValueChangedSignificantly(axis.filter,
7519 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7520 axis.highCurrentValue = axis.highNewValue;
7521 atLeastOneSignificantChange = true;
7522 }
7523 }
7524 }
7525 return atLeastOneSignificantChange;
7526}
7527
7528bool JoystickInputMapper::hasValueChangedSignificantly(
7529 float filter, float newValue, float currentValue, float min, float max) {
7530 if (newValue != currentValue) {
7531 // Filter out small changes in value unless the value is converging on the axis
7532 // bounds or center point. This is intended to reduce the amount of information
7533 // sent to applications by particularly noisy joysticks (such as PS3).
7534 if (fabs(newValue - currentValue) > filter
7535 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7536 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7537 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7538 return true;
7539 }
7540 }
7541 return false;
7542}
7543
7544bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7545 float filter, float newValue, float currentValue, float thresholdValue) {
7546 float newDistance = fabs(newValue - thresholdValue);
7547 if (newDistance < filter) {
7548 float oldDistance = fabs(currentValue - thresholdValue);
7549 if (newDistance < oldDistance) {
7550 return true;
7551 }
7552 }
7553 return false;
7554}
7555
7556} // namespace android