blob: 0cc37a016b856cf48623dba45de98e68d8b673d8 [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;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002785 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 if (moved || scrolled || buttonsChanged) {
2787 mPointerController->setPresentation(
2788 PointerControllerInterface::PRESENTATION_POINTER);
2789
2790 if (moved) {
2791 mPointerController->move(deltaX, deltaY);
2792 }
2793
2794 if (buttonsChanged) {
2795 mPointerController->setButtonState(currentButtonState);
2796 }
2797
2798 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2799 }
2800
2801 float x, y;
2802 mPointerController->getPosition(&x, &y);
2803 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2804 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002807 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 } else {
2809 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2811 displayId = ADISPLAY_ID_NONE;
2812 }
2813
2814 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2815
2816 // Moving an external trackball or mouse should wake the device.
2817 // We don't do this for internal cursor devices to prevent them from waking up
2818 // the device in your pocket.
2819 // TODO: Use the input device configuration to control this behavior more finely.
2820 uint32_t policyFlags = 0;
2821 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002822 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
2824
2825 // Synthesize key down from buttons if needed.
2826 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002827 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828
2829 // Send motion event.
2830 if (downChanged || moved || scrolled || buttonsChanged) {
2831 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002832 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 int32_t motionEventAction;
2834 if (downChanged) {
2835 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002836 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2838 } else {
2839 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2840 }
2841
Michael Wright7b159c92015-05-14 14:48:03 +01002842 if (buttonsReleased) {
2843 BitSet32 released(buttonsReleased);
2844 while (!released.isEmpty()) {
2845 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2846 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002847 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2848 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002849 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002850 metaState, buttonState,
2851 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002852 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002853 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002854 getListener()->notifyMotion(&releaseArgs);
2855 }
2856 }
2857
Prabir Pradhan42611e02018-11-27 14:04:02 -08002858 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2859 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002860 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002861 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002862 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 getListener()->notifyMotion(&args);
2864
Michael Wright7b159c92015-05-14 14:48:03 +01002865 if (buttonsPressed) {
2866 BitSet32 pressed(buttonsPressed);
2867 while (!pressed.isEmpty()) {
2868 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2869 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002870 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2871 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002872 actionButton, 0, metaState, buttonState,
2873 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002874 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002875 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002876 getListener()->notifyMotion(&pressArgs);
2877 }
2878 }
2879
2880 ALOG_ASSERT(buttonState == currentButtonState);
2881
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 // Send hover move after UP to tell the application that the mouse is hovering now.
2883 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002884 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002885 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2886 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002887 metaState, currentButtonState,
2888 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002889 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002890 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891 getListener()->notifyMotion(&hoverArgs);
2892 }
2893
2894 // Send scroll events.
2895 if (scrolled) {
2896 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2897 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2898
Prabir Pradhan42611e02018-11-27 14:04:02 -08002899 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2900 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002901 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002902 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002903 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002904 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002905 getListener()->notifyMotion(&scrollArgs);
2906 }
2907 }
2908
2909 // Synthesize key up from buttons if needed.
2910 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002911 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002912
2913 mCursorMotionAccumulator.finishSync();
2914 mCursorScrollAccumulator.finishSync();
2915}
2916
2917int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2918 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2919 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2920 } else {
2921 return AKEY_STATE_UNKNOWN;
2922 }
2923}
2924
2925void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002926 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002927 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2928 }
2929}
2930
Arthur Hungc23540e2018-11-29 20:42:11 +08002931std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2932 if (mParameters.hasAssociatedDisplay) {
2933 if (mParameters.mode == Parameters::MODE_POINTER) {
2934 return std::make_optional(mPointerController->getDisplayId());
2935 } else {
2936 // If the device is orientationAware and not a mouse,
2937 // it expects to dispatch events to any display
2938 return std::make_optional(ADISPLAY_ID_NONE);
2939 }
2940 }
2941 return std::nullopt;
2942}
2943
Prashant Malani1941ff52015-08-11 18:29:28 -07002944// --- RotaryEncoderInputMapper ---
2945
2946RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002947 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002948 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2949}
2950
2951RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2952}
2953
2954uint32_t RotaryEncoderInputMapper::getSources() {
2955 return mSource;
2956}
2957
2958void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2959 InputMapper::populateDeviceInfo(info);
2960
2961 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002962 float res = 0.0f;
2963 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2964 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2965 }
2966 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2967 mScalingFactor)) {
2968 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2969 "default to 1.0!\n");
2970 mScalingFactor = 1.0f;
2971 }
2972 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2973 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002974 }
2975}
2976
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002977void RotaryEncoderInputMapper::dump(std::string& dump) {
2978 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2979 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002980 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2981}
2982
2983void RotaryEncoderInputMapper::configure(nsecs_t when,
2984 const InputReaderConfiguration* config, uint32_t changes) {
2985 InputMapper::configure(when, config, changes);
2986 if (!changes) {
2987 mRotaryEncoderScrollAccumulator.configure(getDevice());
2988 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002989 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002990 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002991 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002992 if (internalViewport) {
2993 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002994 } else {
2995 mOrientation = DISPLAY_ORIENTATION_0;
2996 }
2997 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002998}
2999
3000void RotaryEncoderInputMapper::reset(nsecs_t when) {
3001 mRotaryEncoderScrollAccumulator.reset(getDevice());
3002
3003 InputMapper::reset(when);
3004}
3005
3006void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3007 mRotaryEncoderScrollAccumulator.process(rawEvent);
3008
3009 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3010 sync(rawEvent->when);
3011 }
3012}
3013
3014void RotaryEncoderInputMapper::sync(nsecs_t when) {
3015 PointerCoords pointerCoords;
3016 pointerCoords.clear();
3017
3018 PointerProperties pointerProperties;
3019 pointerProperties.clear();
3020 pointerProperties.id = 0;
3021 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3022
3023 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3024 bool scrolled = scroll != 0;
3025
3026 // This is not a pointer, so it's not associated with a display.
3027 int32_t displayId = ADISPLAY_ID_NONE;
3028
3029 // Moving the rotary encoder should wake the device (if specified).
3030 uint32_t policyFlags = 0;
3031 if (scrolled && getDevice()->isExternal()) {
3032 policyFlags |= POLICY_FLAG_WAKE;
3033 }
3034
Ivan Podogovad437252016-09-29 16:29:55 +01003035 if (mOrientation == DISPLAY_ORIENTATION_180) {
3036 scroll = -scroll;
3037 }
3038
Prashant Malani1941ff52015-08-11 18:29:28 -07003039 // Send motion event.
3040 if (scrolled) {
3041 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003042 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003043
Prabir Pradhan42611e02018-11-27 14:04:02 -08003044 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3045 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08003046 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0,
3047 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003048 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003049 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003050 getListener()->notifyMotion(&scrollArgs);
3051 }
3052
3053 mRotaryEncoderScrollAccumulator.finishSync();
3054}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003055
3056// --- TouchInputMapper ---
3057
3058TouchInputMapper::TouchInputMapper(InputDevice* device) :
3059 InputMapper(device),
3060 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3061 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003062 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003063 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3064}
3065
3066TouchInputMapper::~TouchInputMapper() {
3067}
3068
3069uint32_t TouchInputMapper::getSources() {
3070 return mSource;
3071}
3072
3073void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3074 InputMapper::populateDeviceInfo(info);
3075
3076 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3077 info->addMotionRange(mOrientedRanges.x);
3078 info->addMotionRange(mOrientedRanges.y);
3079 info->addMotionRange(mOrientedRanges.pressure);
3080
3081 if (mOrientedRanges.haveSize) {
3082 info->addMotionRange(mOrientedRanges.size);
3083 }
3084
3085 if (mOrientedRanges.haveTouchSize) {
3086 info->addMotionRange(mOrientedRanges.touchMajor);
3087 info->addMotionRange(mOrientedRanges.touchMinor);
3088 }
3089
3090 if (mOrientedRanges.haveToolSize) {
3091 info->addMotionRange(mOrientedRanges.toolMajor);
3092 info->addMotionRange(mOrientedRanges.toolMinor);
3093 }
3094
3095 if (mOrientedRanges.haveOrientation) {
3096 info->addMotionRange(mOrientedRanges.orientation);
3097 }
3098
3099 if (mOrientedRanges.haveDistance) {
3100 info->addMotionRange(mOrientedRanges.distance);
3101 }
3102
3103 if (mOrientedRanges.haveTilt) {
3104 info->addMotionRange(mOrientedRanges.tilt);
3105 }
3106
3107 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3108 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3109 0.0f);
3110 }
3111 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3112 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3113 0.0f);
3114 }
3115 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3116 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3117 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3118 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3119 x.fuzz, x.resolution);
3120 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3121 y.fuzz, y.resolution);
3122 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3123 x.fuzz, x.resolution);
3124 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3125 y.fuzz, y.resolution);
3126 }
3127 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3128 }
3129}
3130
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003131void TouchInputMapper::dump(std::string& dump) {
3132 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003133 dumpParameters(dump);
3134 dumpVirtualKeys(dump);
3135 dumpRawPointerAxes(dump);
3136 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003137 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 dumpSurface(dump);
3139
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003140 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3141 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3142 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3143 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3144 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3145 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3146 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3147 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3148 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3149 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3150 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3151 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3152 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3153 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3154 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3155 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3156 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003157
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003158 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3159 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003160 mLastRawState.rawPointerData.pointerCount);
3161 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3162 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003163 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3165 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3166 "toolType=%d, isHovering=%s\n", i,
3167 pointer.id, pointer.x, pointer.y, pointer.pressure,
3168 pointer.touchMajor, pointer.touchMinor,
3169 pointer.toolMajor, pointer.toolMinor,
3170 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3171 pointer.toolType, toString(pointer.isHovering));
3172 }
3173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3175 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003176 mLastCookedState.cookedPointerData.pointerCount);
3177 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3178 const PointerProperties& pointerProperties =
3179 mLastCookedState.cookedPointerData.pointerProperties[i];
3180 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3183 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3184 "toolType=%d, isHovering=%s\n", i,
3185 pointerProperties.id,
3186 pointerCoords.getX(),
3187 pointerCoords.getY(),
3188 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3189 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3190 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3191 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3192 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3193 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3194 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3195 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3196 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003197 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 }
3199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003200 dump += INDENT3 "Stylus Fusion:\n";
3201 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003202 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003203 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3204 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003205 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003206 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003207 dumpStylusState(dump, mExternalStylusState);
3208
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003210 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3211 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003212 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003213 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003215 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003216 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003219 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 mPointerGestureMaxSwipeWidth);
3221 }
3222}
3223
Santos Cordonfa5cf462017-04-05 10:37:00 -07003224const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3225 switch (deviceMode) {
3226 case DEVICE_MODE_DISABLED:
3227 return "disabled";
3228 case DEVICE_MODE_DIRECT:
3229 return "direct";
3230 case DEVICE_MODE_UNSCALED:
3231 return "unscaled";
3232 case DEVICE_MODE_NAVIGATION:
3233 return "navigation";
3234 case DEVICE_MODE_POINTER:
3235 return "pointer";
3236 }
3237 return "unknown";
3238}
3239
Michael Wrightd02c5b62014-02-10 15:10:22 -08003240void TouchInputMapper::configure(nsecs_t when,
3241 const InputReaderConfiguration* config, uint32_t changes) {
3242 InputMapper::configure(when, config, changes);
3243
3244 mConfig = *config;
3245
3246 if (!changes) { // first time only
3247 // Configure basic parameters.
3248 configureParameters();
3249
3250 // Configure common accumulators.
3251 mCursorScrollAccumulator.configure(getDevice());
3252 mTouchButtonAccumulator.configure(getDevice());
3253
3254 // Configure absolute axis information.
3255 configureRawPointerAxes();
3256
3257 // Prepare input device calibration.
3258 parseCalibration();
3259 resolveCalibration();
3260 }
3261
Michael Wright842500e2015-03-13 17:32:02 -07003262 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003263 // Update location calibration to reflect current settings
3264 updateAffineTransformation();
3265 }
3266
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3268 // Update pointer speed.
3269 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3270 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3271 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3272 }
3273
3274 bool resetNeeded = false;
3275 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3276 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003277 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3278 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279 // Configure device sources, surface dimensions, orientation and
3280 // scaling factors.
3281 configureSurface(when, &resetNeeded);
3282 }
3283
3284 if (changes && resetNeeded) {
3285 // Send reset, unless this is the first time the device has been configured,
3286 // in which case the reader will call reset itself after all mappers are ready.
3287 getDevice()->notifyReset(when);
3288 }
3289}
3290
Michael Wright842500e2015-03-13 17:32:02 -07003291void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003292 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003293 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003294 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003295
3296 if (!mExternalStylusConnected) {
3297 resetExternalStylus();
3298 }
3299}
3300
Michael Wrightd02c5b62014-02-10 15:10:22 -08003301void TouchInputMapper::configureParameters() {
3302 // Use the pointer presentation mode for devices that do not support distinct
3303 // multitouch. The spot-based presentation relies on being able to accurately
3304 // locate two or more fingers on the touch pad.
3305 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003306 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307
3308 String8 gestureModeString;
3309 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3310 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003311 if (gestureModeString == "single-touch") {
3312 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3313 } else if (gestureModeString == "multi-touch") {
3314 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003315 } else if (gestureModeString != "default") {
3316 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3317 }
3318 }
3319
3320 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3321 // The device is a touch screen.
3322 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3323 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3324 // The device is a pointing device like a track pad.
3325 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3326 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3327 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3328 // The device is a cursor device with a touch pad attached.
3329 // By default don't use the touch pad to move the pointer.
3330 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3331 } else {
3332 // The device is a touch pad of unknown purpose.
3333 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3334 }
3335
3336 mParameters.hasButtonUnderPad=
3337 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3338
3339 String8 deviceTypeString;
3340 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3341 deviceTypeString)) {
3342 if (deviceTypeString == "touchScreen") {
3343 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3344 } else if (deviceTypeString == "touchPad") {
3345 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3346 } else if (deviceTypeString == "touchNavigation") {
3347 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3348 } else if (deviceTypeString == "pointer") {
3349 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3350 } else if (deviceTypeString != "default") {
3351 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3352 }
3353 }
3354
3355 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3356 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3357 mParameters.orientationAware);
3358
3359 mParameters.hasAssociatedDisplay = false;
3360 mParameters.associatedDisplayIsExternal = false;
3361 if (mParameters.orientationAware
3362 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3363 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3364 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003365 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3366 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003367 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003368 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003369 uniqueDisplayId);
3370 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003373 if (getDevice()->getAssociatedDisplayPort()) {
3374 mParameters.hasAssociatedDisplay = true;
3375 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003376
3377 // Initial downs on external touch devices should wake the device.
3378 // Normally we don't do this for internal touch screens to prevent them from waking
3379 // up in your pocket but you can enable it using the input device configuration.
3380 mParameters.wake = getDevice()->isExternal();
3381 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3382 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383}
3384
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003385void TouchInputMapper::dumpParameters(std::string& dump) {
3386 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387
3388 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003389 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003392 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003393 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394 break;
3395 default:
3396 assert(false);
3397 }
3398
3399 switch (mParameters.deviceType) {
3400 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003401 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 break;
3403 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003404 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 break;
3406 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 break;
3409 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003410 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 break;
3412 default:
3413 ALOG_ASSERT(false);
3414 }
3415
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003416 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003417 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003419 toString(mParameters.associatedDisplayIsExternal),
3420 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 toString(mParameters.orientationAware));
3423}
3424
3425void TouchInputMapper::configureRawPointerAxes() {
3426 mRawPointerAxes.clear();
3427}
3428
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003429void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3430 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003431 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3432 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3433 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3434 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3435 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3436 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3437 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3438 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3439 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3440 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3441 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3444}
3445
Michael Wright842500e2015-03-13 17:32:02 -07003446bool TouchInputMapper::hasExternalStylus() const {
3447 return mExternalStylusConnected;
3448}
3449
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003450/**
3451 * Determine which DisplayViewport to use.
3452 * 1. If display port is specified, return the matching viewport. If matching viewport not
3453 * found, then return.
3454 * 2. If a device has associated display, get the matching viewport by either unique id or by
3455 * the display type (internal or external).
3456 * 3. Otherwise, use a non-display viewport.
3457 */
3458std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3459 if (mParameters.hasAssociatedDisplay) {
3460 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3461 if (displayPort) {
3462 // Find the viewport that contains the same port
3463 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3464 if (!v) {
3465 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3466 "but the corresponding viewport is not found.",
3467 getDeviceName().c_str(), *displayPort);
3468 }
3469 return v;
3470 }
3471
3472 if (!mParameters.uniqueDisplayId.empty()) {
3473 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3474 }
3475
3476 ViewportType viewportTypeToUse;
3477 if (mParameters.associatedDisplayIsExternal) {
3478 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3479 } else {
3480 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3481 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003482
3483 std::optional<DisplayViewport> viewport =
3484 mConfig.getDisplayViewportByType(viewportTypeToUse);
3485 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3486 ALOGW("Input device %s should be associated with external display, "
3487 "fallback to internal one for the external viewport is not found.",
3488 getDeviceName().c_str());
3489 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3490 }
3491
3492 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003493 }
3494
3495 DisplayViewport newViewport;
3496 // Raw width and height in the natural orientation.
3497 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3498 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3499 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3500 return std::make_optional(newViewport);
3501}
3502
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3504 int32_t oldDeviceMode = mDeviceMode;
3505
Michael Wright842500e2015-03-13 17:32:02 -07003506 resolveExternalStylusPresence();
3507
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 // Determine device mode.
3509 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3510 && mConfig.pointerGesturesEnabled) {
3511 mSource = AINPUT_SOURCE_MOUSE;
3512 mDeviceMode = DEVICE_MODE_POINTER;
3513 if (hasStylus()) {
3514 mSource |= AINPUT_SOURCE_STYLUS;
3515 }
3516 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3517 && mParameters.hasAssociatedDisplay) {
3518 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3519 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003520 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 mSource |= AINPUT_SOURCE_STYLUS;
3522 }
Michael Wright2f78b682015-06-12 15:25:08 +01003523 if (hasExternalStylus()) {
3524 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3525 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3527 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3528 mDeviceMode = DEVICE_MODE_NAVIGATION;
3529 } else {
3530 mSource = AINPUT_SOURCE_TOUCHPAD;
3531 mDeviceMode = DEVICE_MODE_UNSCALED;
3532 }
3533
3534 // Ensure we have valid X and Y axes.
3535 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003536 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003537 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538 mDeviceMode = DEVICE_MODE_DISABLED;
3539 return;
3540 }
3541
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003542 // Get associated display dimensions.
3543 std::optional<DisplayViewport> newViewport = findViewport();
3544 if (!newViewport) {
3545 ALOGI("Touch device '%s' could not query the properties of its associated "
3546 "display. The device will be inoperable until the display size "
3547 "becomes available.",
3548 getDeviceName().c_str());
3549 mDeviceMode = DEVICE_MODE_DISABLED;
3550 return;
3551 }
3552
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003554 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3555 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003556
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003557 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003559 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003560
3561 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3562 // Convert rotated viewport to natural surface coordinates.
3563 int32_t naturalLogicalWidth, naturalLogicalHeight;
3564 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3565 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3566 int32_t naturalDeviceWidth, naturalDeviceHeight;
3567 switch (mViewport.orientation) {
3568 case DISPLAY_ORIENTATION_90:
3569 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3570 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3571 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3572 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3573 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3574 naturalPhysicalTop = mViewport.physicalLeft;
3575 naturalDeviceWidth = mViewport.deviceHeight;
3576 naturalDeviceHeight = mViewport.deviceWidth;
3577 break;
3578 case DISPLAY_ORIENTATION_180:
3579 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3580 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3581 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3582 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3583 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3584 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3585 naturalDeviceWidth = mViewport.deviceWidth;
3586 naturalDeviceHeight = mViewport.deviceHeight;
3587 break;
3588 case DISPLAY_ORIENTATION_270:
3589 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3590 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3591 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3592 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3593 naturalPhysicalLeft = mViewport.physicalTop;
3594 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3595 naturalDeviceWidth = mViewport.deviceHeight;
3596 naturalDeviceHeight = mViewport.deviceWidth;
3597 break;
3598 case DISPLAY_ORIENTATION_0:
3599 default:
3600 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3601 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3602 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3603 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3604 naturalPhysicalLeft = mViewport.physicalLeft;
3605 naturalPhysicalTop = mViewport.physicalTop;
3606 naturalDeviceWidth = mViewport.deviceWidth;
3607 naturalDeviceHeight = mViewport.deviceHeight;
3608 break;
3609 }
3610
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003611 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3612 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3613 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3614 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3615 }
3616
Michael Wright358bcc72018-08-21 04:01:07 +01003617 mPhysicalWidth = naturalPhysicalWidth;
3618 mPhysicalHeight = naturalPhysicalHeight;
3619 mPhysicalLeft = naturalPhysicalLeft;
3620 mPhysicalTop = naturalPhysicalTop;
3621
Michael Wrightd02c5b62014-02-10 15:10:22 -08003622 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3623 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3624 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3625 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3626
3627 mSurfaceOrientation = mParameters.orientationAware ?
3628 mViewport.orientation : DISPLAY_ORIENTATION_0;
3629 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003630 mPhysicalWidth = rawWidth;
3631 mPhysicalHeight = rawHeight;
3632 mPhysicalLeft = 0;
3633 mPhysicalTop = 0;
3634
Michael Wrightd02c5b62014-02-10 15:10:22 -08003635 mSurfaceWidth = rawWidth;
3636 mSurfaceHeight = rawHeight;
3637 mSurfaceLeft = 0;
3638 mSurfaceTop = 0;
3639 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3640 }
3641 }
3642
3643 // If moving between pointer modes, need to reset some state.
3644 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3645 if (deviceModeChanged) {
3646 mOrientedRanges.clear();
3647 }
3648
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003649 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 if (mDeviceMode == DEVICE_MODE_POINTER ||
3651 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003652 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003653 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3654 }
3655 } else {
3656 mPointerController.clear();
3657 }
3658
3659 if (viewportChanged || deviceModeChanged) {
3660 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3661 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003662 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003663 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3664
3665 // Configure X and Y factors.
3666 mXScale = float(mSurfaceWidth) / rawWidth;
3667 mYScale = float(mSurfaceHeight) / rawHeight;
3668 mXTranslate = -mSurfaceLeft;
3669 mYTranslate = -mSurfaceTop;
3670 mXPrecision = 1.0f / mXScale;
3671 mYPrecision = 1.0f / mYScale;
3672
3673 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3674 mOrientedRanges.x.source = mSource;
3675 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3676 mOrientedRanges.y.source = mSource;
3677
3678 configureVirtualKeys();
3679
3680 // Scale factor for terms that are not oriented in a particular axis.
3681 // If the pixels are square then xScale == yScale otherwise we fake it
3682 // by choosing an average.
3683 mGeometricScale = avg(mXScale, mYScale);
3684
3685 // Size of diagonal axis.
3686 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3687
3688 // Size factors.
3689 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3690 if (mRawPointerAxes.touchMajor.valid
3691 && mRawPointerAxes.touchMajor.maxValue != 0) {
3692 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3693 } else if (mRawPointerAxes.toolMajor.valid
3694 && mRawPointerAxes.toolMajor.maxValue != 0) {
3695 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3696 } else {
3697 mSizeScale = 0.0f;
3698 }
3699
3700 mOrientedRanges.haveTouchSize = true;
3701 mOrientedRanges.haveToolSize = true;
3702 mOrientedRanges.haveSize = true;
3703
3704 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3705 mOrientedRanges.touchMajor.source = mSource;
3706 mOrientedRanges.touchMajor.min = 0;
3707 mOrientedRanges.touchMajor.max = diagonalSize;
3708 mOrientedRanges.touchMajor.flat = 0;
3709 mOrientedRanges.touchMajor.fuzz = 0;
3710 mOrientedRanges.touchMajor.resolution = 0;
3711
3712 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3713 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3714
3715 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3716 mOrientedRanges.toolMajor.source = mSource;
3717 mOrientedRanges.toolMajor.min = 0;
3718 mOrientedRanges.toolMajor.max = diagonalSize;
3719 mOrientedRanges.toolMajor.flat = 0;
3720 mOrientedRanges.toolMajor.fuzz = 0;
3721 mOrientedRanges.toolMajor.resolution = 0;
3722
3723 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3724 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3725
3726 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3727 mOrientedRanges.size.source = mSource;
3728 mOrientedRanges.size.min = 0;
3729 mOrientedRanges.size.max = 1.0;
3730 mOrientedRanges.size.flat = 0;
3731 mOrientedRanges.size.fuzz = 0;
3732 mOrientedRanges.size.resolution = 0;
3733 } else {
3734 mSizeScale = 0.0f;
3735 }
3736
3737 // Pressure factors.
3738 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003739 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003740 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3741 || mCalibration.pressureCalibration
3742 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3743 if (mCalibration.havePressureScale) {
3744 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003745 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 } else if (mRawPointerAxes.pressure.valid
3747 && mRawPointerAxes.pressure.maxValue != 0) {
3748 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3749 }
3750 }
3751
3752 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3753 mOrientedRanges.pressure.source = mSource;
3754 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003755 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003756 mOrientedRanges.pressure.flat = 0;
3757 mOrientedRanges.pressure.fuzz = 0;
3758 mOrientedRanges.pressure.resolution = 0;
3759
3760 // Tilt
3761 mTiltXCenter = 0;
3762 mTiltXScale = 0;
3763 mTiltYCenter = 0;
3764 mTiltYScale = 0;
3765 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3766 if (mHaveTilt) {
3767 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3768 mRawPointerAxes.tiltX.maxValue);
3769 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3770 mRawPointerAxes.tiltY.maxValue);
3771 mTiltXScale = M_PI / 180;
3772 mTiltYScale = M_PI / 180;
3773
3774 mOrientedRanges.haveTilt = true;
3775
3776 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3777 mOrientedRanges.tilt.source = mSource;
3778 mOrientedRanges.tilt.min = 0;
3779 mOrientedRanges.tilt.max = M_PI_2;
3780 mOrientedRanges.tilt.flat = 0;
3781 mOrientedRanges.tilt.fuzz = 0;
3782 mOrientedRanges.tilt.resolution = 0;
3783 }
3784
3785 // Orientation
3786 mOrientationScale = 0;
3787 if (mHaveTilt) {
3788 mOrientedRanges.haveOrientation = true;
3789
3790 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3791 mOrientedRanges.orientation.source = mSource;
3792 mOrientedRanges.orientation.min = -M_PI;
3793 mOrientedRanges.orientation.max = M_PI;
3794 mOrientedRanges.orientation.flat = 0;
3795 mOrientedRanges.orientation.fuzz = 0;
3796 mOrientedRanges.orientation.resolution = 0;
3797 } else if (mCalibration.orientationCalibration !=
3798 Calibration::ORIENTATION_CALIBRATION_NONE) {
3799 if (mCalibration.orientationCalibration
3800 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3801 if (mRawPointerAxes.orientation.valid) {
3802 if (mRawPointerAxes.orientation.maxValue > 0) {
3803 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3804 } else if (mRawPointerAxes.orientation.minValue < 0) {
3805 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3806 } else {
3807 mOrientationScale = 0;
3808 }
3809 }
3810 }
3811
3812 mOrientedRanges.haveOrientation = true;
3813
3814 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3815 mOrientedRanges.orientation.source = mSource;
3816 mOrientedRanges.orientation.min = -M_PI_2;
3817 mOrientedRanges.orientation.max = M_PI_2;
3818 mOrientedRanges.orientation.flat = 0;
3819 mOrientedRanges.orientation.fuzz = 0;
3820 mOrientedRanges.orientation.resolution = 0;
3821 }
3822
3823 // Distance
3824 mDistanceScale = 0;
3825 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3826 if (mCalibration.distanceCalibration
3827 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3828 if (mCalibration.haveDistanceScale) {
3829 mDistanceScale = mCalibration.distanceScale;
3830 } else {
3831 mDistanceScale = 1.0f;
3832 }
3833 }
3834
3835 mOrientedRanges.haveDistance = true;
3836
3837 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3838 mOrientedRanges.distance.source = mSource;
3839 mOrientedRanges.distance.min =
3840 mRawPointerAxes.distance.minValue * mDistanceScale;
3841 mOrientedRanges.distance.max =
3842 mRawPointerAxes.distance.maxValue * mDistanceScale;
3843 mOrientedRanges.distance.flat = 0;
3844 mOrientedRanges.distance.fuzz =
3845 mRawPointerAxes.distance.fuzz * mDistanceScale;
3846 mOrientedRanges.distance.resolution = 0;
3847 }
3848
3849 // Compute oriented precision, scales and ranges.
3850 // Note that the maximum value reported is an inclusive maximum value so it is one
3851 // unit less than the total width or height of surface.
3852 switch (mSurfaceOrientation) {
3853 case DISPLAY_ORIENTATION_90:
3854 case DISPLAY_ORIENTATION_270:
3855 mOrientedXPrecision = mYPrecision;
3856 mOrientedYPrecision = mXPrecision;
3857
3858 mOrientedRanges.x.min = mYTranslate;
3859 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3860 mOrientedRanges.x.flat = 0;
3861 mOrientedRanges.x.fuzz = 0;
3862 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3863
3864 mOrientedRanges.y.min = mXTranslate;
3865 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3866 mOrientedRanges.y.flat = 0;
3867 mOrientedRanges.y.fuzz = 0;
3868 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3869 break;
3870
3871 default:
3872 mOrientedXPrecision = mXPrecision;
3873 mOrientedYPrecision = mYPrecision;
3874
3875 mOrientedRanges.x.min = mXTranslate;
3876 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3877 mOrientedRanges.x.flat = 0;
3878 mOrientedRanges.x.fuzz = 0;
3879 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3880
3881 mOrientedRanges.y.min = mYTranslate;
3882 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3883 mOrientedRanges.y.flat = 0;
3884 mOrientedRanges.y.fuzz = 0;
3885 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3886 break;
3887 }
3888
Jason Gerecke71b16e82014-03-10 09:47:59 -07003889 // Location
3890 updateAffineTransformation();
3891
Michael Wrightd02c5b62014-02-10 15:10:22 -08003892 if (mDeviceMode == DEVICE_MODE_POINTER) {
3893 // Compute pointer gesture detection parameters.
3894 float rawDiagonal = hypotf(rawWidth, rawHeight);
3895 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3896
3897 // Scale movements such that one whole swipe of the touch pad covers a
3898 // given area relative to the diagonal size of the display when no acceleration
3899 // is applied.
3900 // Assume that the touch pad has a square aspect ratio such that movements in
3901 // X and Y of the same number of raw units cover the same physical distance.
3902 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3903 * displayDiagonal / rawDiagonal;
3904 mPointerYMovementScale = mPointerXMovementScale;
3905
3906 // Scale zooms to cover a smaller range of the display than movements do.
3907 // This value determines the area around the pointer that is affected by freeform
3908 // pointer gestures.
3909 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3910 * displayDiagonal / rawDiagonal;
3911 mPointerYZoomScale = mPointerXZoomScale;
3912
3913 // Max width between pointers to detect a swipe gesture is more than some fraction
3914 // of the diagonal axis of the touch pad. Touches that are wider than this are
3915 // translated into freeform gestures.
3916 mPointerGestureMaxSwipeWidth =
3917 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3918
3919 // Abort current pointer usages because the state has changed.
3920 abortPointerUsage(when, 0 /*policyFlags*/);
3921 }
3922
3923 // Inform the dispatcher about the changes.
3924 *outResetNeeded = true;
3925 bumpGeneration();
3926 }
3927}
3928
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003929void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003930 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003931 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3932 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3933 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3934 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003935 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3936 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3937 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3938 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003939 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003940}
3941
3942void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003943 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003944 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3945
3946 mVirtualKeys.clear();
3947
3948 if (virtualKeyDefinitions.size() == 0) {
3949 return;
3950 }
3951
Michael Wrightd02c5b62014-02-10 15:10:22 -08003952 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3953 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003954 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3955 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003956
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003957 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3958 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
3960 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3961 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003962 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003964 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3965 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3967 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003968 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 }
3970
3971 virtualKey.keyCode = keyCode;
3972 virtualKey.flags = flags;
3973
3974 // convert the key definition's display coordinates into touch coordinates for a hit box
3975 int32_t halfWidth = virtualKeyDefinition.width / 2;
3976 int32_t halfHeight = virtualKeyDefinition.height / 2;
3977
3978 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3979 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3980 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3981 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3982 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3983 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3984 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3985 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003986 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003987 }
3988}
3989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003990void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003991 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003992 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993
3994 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003995 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003996 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003997 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3998 i, virtualKey.scanCode, virtualKey.keyCode,
3999 virtualKey.hitLeft, virtualKey.hitRight,
4000 virtualKey.hitTop, virtualKey.hitBottom);
4001 }
4002 }
4003}
4004
4005void TouchInputMapper::parseCalibration() {
4006 const PropertyMap& in = getDevice()->getConfiguration();
4007 Calibration& out = mCalibration;
4008
4009 // Size
4010 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4011 String8 sizeCalibrationString;
4012 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4013 if (sizeCalibrationString == "none") {
4014 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4015 } else if (sizeCalibrationString == "geometric") {
4016 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4017 } else if (sizeCalibrationString == "diameter") {
4018 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4019 } else if (sizeCalibrationString == "box") {
4020 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4021 } else if (sizeCalibrationString == "area") {
4022 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4023 } else if (sizeCalibrationString != "default") {
4024 ALOGW("Invalid value for touch.size.calibration: '%s'",
4025 sizeCalibrationString.string());
4026 }
4027 }
4028
4029 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4030 out.sizeScale);
4031 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4032 out.sizeBias);
4033 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4034 out.sizeIsSummed);
4035
4036 // Pressure
4037 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4038 String8 pressureCalibrationString;
4039 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4040 if (pressureCalibrationString == "none") {
4041 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4042 } else if (pressureCalibrationString == "physical") {
4043 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4044 } else if (pressureCalibrationString == "amplitude") {
4045 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4046 } else if (pressureCalibrationString != "default") {
4047 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4048 pressureCalibrationString.string());
4049 }
4050 }
4051
4052 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4053 out.pressureScale);
4054
4055 // Orientation
4056 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4057 String8 orientationCalibrationString;
4058 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4059 if (orientationCalibrationString == "none") {
4060 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4061 } else if (orientationCalibrationString == "interpolated") {
4062 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4063 } else if (orientationCalibrationString == "vector") {
4064 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4065 } else if (orientationCalibrationString != "default") {
4066 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4067 orientationCalibrationString.string());
4068 }
4069 }
4070
4071 // Distance
4072 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4073 String8 distanceCalibrationString;
4074 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4075 if (distanceCalibrationString == "none") {
4076 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4077 } else if (distanceCalibrationString == "scaled") {
4078 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4079 } else if (distanceCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4081 distanceCalibrationString.string());
4082 }
4083 }
4084
4085 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4086 out.distanceScale);
4087
4088 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4089 String8 coverageCalibrationString;
4090 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4091 if (coverageCalibrationString == "none") {
4092 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4093 } else if (coverageCalibrationString == "box") {
4094 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4095 } else if (coverageCalibrationString != "default") {
4096 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4097 coverageCalibrationString.string());
4098 }
4099 }
4100}
4101
4102void TouchInputMapper::resolveCalibration() {
4103 // Size
4104 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4105 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4106 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4107 }
4108 } else {
4109 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4110 }
4111
4112 // Pressure
4113 if (mRawPointerAxes.pressure.valid) {
4114 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4115 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4116 }
4117 } else {
4118 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4119 }
4120
4121 // Orientation
4122 if (mRawPointerAxes.orientation.valid) {
4123 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4124 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4125 }
4126 } else {
4127 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4128 }
4129
4130 // Distance
4131 if (mRawPointerAxes.distance.valid) {
4132 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4133 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4134 }
4135 } else {
4136 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4137 }
4138
4139 // Coverage
4140 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4141 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4142 }
4143}
4144
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004145void TouchInputMapper::dumpCalibration(std::string& dump) {
4146 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147
4148 // Size
4149 switch (mCalibration.sizeCalibration) {
4150 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 break;
4153 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 break;
4156 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 break;
4159 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 break;
4162 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 break;
4165 default:
4166 ALOG_ASSERT(false);
4167 }
4168
4169 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 mCalibration.sizeScale);
4172 }
4173
4174 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004175 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 mCalibration.sizeBias);
4177 }
4178
4179 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 toString(mCalibration.sizeIsSummed));
4182 }
4183
4184 // Pressure
4185 switch (mCalibration.pressureCalibration) {
4186 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004187 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 break;
4189 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004190 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 break;
4192 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 break;
4195 default:
4196 ALOG_ASSERT(false);
4197 }
4198
4199 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004200 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 mCalibration.pressureScale);
4202 }
4203
4204 // Orientation
4205 switch (mCalibration.orientationCalibration) {
4206 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004208 break;
4209 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004210 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 break;
4212 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 break;
4215 default:
4216 ALOG_ASSERT(false);
4217 }
4218
4219 // Distance
4220 switch (mCalibration.distanceCalibration) {
4221 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004222 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 break;
4224 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 break;
4227 default:
4228 ALOG_ASSERT(false);
4229 }
4230
4231 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004233 mCalibration.distanceScale);
4234 }
4235
4236 switch (mCalibration.coverageCalibration) {
4237 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004238 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 break;
4240 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004241 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 break;
4243 default:
4244 ALOG_ASSERT(false);
4245 }
4246}
4247
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004248void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4249 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004250
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004251 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4252 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4253 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4254 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4255 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4256 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004257}
4258
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004259void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004260 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4261 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004262}
4263
Michael Wrightd02c5b62014-02-10 15:10:22 -08004264void TouchInputMapper::reset(nsecs_t when) {
4265 mCursorButtonAccumulator.reset(getDevice());
4266 mCursorScrollAccumulator.reset(getDevice());
4267 mTouchButtonAccumulator.reset(getDevice());
4268
4269 mPointerVelocityControl.reset();
4270 mWheelXVelocityControl.reset();
4271 mWheelYVelocityControl.reset();
4272
Michael Wright842500e2015-03-13 17:32:02 -07004273 mRawStatesPending.clear();
4274 mCurrentRawState.clear();
4275 mCurrentCookedState.clear();
4276 mLastRawState.clear();
4277 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004278 mPointerUsage = POINTER_USAGE_NONE;
4279 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004280 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004281 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282 mDownTime = 0;
4283
4284 mCurrentVirtualKey.down = false;
4285
4286 mPointerGesture.reset();
4287 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004288 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289
Yi Kong9b14ac62018-07-17 13:48:38 -07004290 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004291 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4292 mPointerController->clearSpots();
4293 }
4294
4295 InputMapper::reset(when);
4296}
4297
Michael Wright842500e2015-03-13 17:32:02 -07004298void TouchInputMapper::resetExternalStylus() {
4299 mExternalStylusState.clear();
4300 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004301 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004302 mExternalStylusDataPending = false;
4303}
4304
Michael Wright43fd19f2015-04-21 19:02:58 +01004305void TouchInputMapper::clearStylusDataPendingFlags() {
4306 mExternalStylusDataPending = false;
4307 mExternalStylusFusionTimeout = LLONG_MAX;
4308}
4309
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004310void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4311 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4312 nsecs_t latency = now - evdevTime;
4313 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4314 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4315 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4316 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
4317 mStatistics.min, mStatistics.max, mStatistics.mean(), mStatistics.stdev());
4318 mStatistics.reset(now);
4319 }
4320}
4321
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322void TouchInputMapper::process(const RawEvent* rawEvent) {
4323 mCursorButtonAccumulator.process(rawEvent);
4324 mCursorScrollAccumulator.process(rawEvent);
4325 mTouchButtonAccumulator.process(rawEvent);
4326
4327 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004328 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 sync(rawEvent->when);
4330 }
4331}
4332
4333void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004334 const RawState* last = mRawStatesPending.empty() ?
4335 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004336
4337 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004338 mRawStatesPending.emplace_back();
4339
4340 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004341 next->clear();
4342 next->when = when;
4343
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004345 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004346 | mCursorButtonAccumulator.getButtonState();
4347
Michael Wright842500e2015-03-13 17:32:02 -07004348 // Sync scroll
4349 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4350 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 mCursorScrollAccumulator.finishSync();
4352
Michael Wright842500e2015-03-13 17:32:02 -07004353 // Sync touch
4354 syncTouch(when, next);
4355
4356 // Assign pointer ids.
4357 if (!mHavePointerIds) {
4358 assignPointerIds(last, next);
4359 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360
4361#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004362 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4363 "hovering ids 0x%08x -> 0x%08x",
4364 last->rawPointerData.pointerCount,
4365 next->rawPointerData.pointerCount,
4366 last->rawPointerData.touchingIdBits.value,
4367 next->rawPointerData.touchingIdBits.value,
4368 last->rawPointerData.hoveringIdBits.value,
4369 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004370#endif
4371
Michael Wright842500e2015-03-13 17:32:02 -07004372 processRawTouches(false /*timeout*/);
4373}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004374
Michael Wright842500e2015-03-13 17:32:02 -07004375void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4377 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004378 mCurrentRawState.clear();
4379 mRawStatesPending.clear();
4380 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381 }
4382
Michael Wright842500e2015-03-13 17:32:02 -07004383 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4384 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4385 // touching the current state will only observe the events that have been dispatched to the
4386 // rest of the pipeline.
4387 const size_t N = mRawStatesPending.size();
4388 size_t count;
4389 for(count = 0; count < N; count++) {
4390 const RawState& next = mRawStatesPending[count];
4391
4392 // A failure to assign the stylus id means that we're waiting on stylus data
4393 // and so should defer the rest of the pipeline.
4394 if (assignExternalStylusId(next, timeout)) {
4395 break;
4396 }
4397
4398 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004399 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004400 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004401 if (mCurrentRawState.when < mLastRawState.when) {
4402 mCurrentRawState.when = mLastRawState.when;
4403 }
Michael Wright842500e2015-03-13 17:32:02 -07004404 cookAndDispatch(mCurrentRawState.when);
4405 }
4406 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004407 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004408 }
4409
Michael Wright842500e2015-03-13 17:32:02 -07004410 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004411 if (timeout) {
4412 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4413 clearStylusDataPendingFlags();
4414 mCurrentRawState.copyFrom(mLastRawState);
4415#if DEBUG_STYLUS_FUSION
4416 ALOGD("Timeout expired, synthesizing event with new stylus data");
4417#endif
4418 cookAndDispatch(when);
4419 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4420 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4421 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4422 }
Michael Wright842500e2015-03-13 17:32:02 -07004423 }
4424}
4425
4426void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4427 // Always start with a clean state.
4428 mCurrentCookedState.clear();
4429
4430 // Apply stylus buttons to current raw state.
4431 applyExternalStylusButtonState(when);
4432
4433 // Handle policy on initial down or hover events.
4434 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4435 && mCurrentRawState.rawPointerData.pointerCount != 0;
4436
4437 uint32_t policyFlags = 0;
4438 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4439 if (initialDown || buttonsPressed) {
4440 // If this is a touch screen, hide the pointer on an initial down.
4441 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4442 getContext()->fadePointer();
4443 }
4444
4445 if (mParameters.wake) {
4446 policyFlags |= POLICY_FLAG_WAKE;
4447 }
4448 }
4449
4450 // Consume raw off-screen touches before cooking pointer data.
4451 // If touches are consumed, subsequent code will not receive any pointer data.
4452 if (consumeRawTouches(when, policyFlags)) {
4453 mCurrentRawState.rawPointerData.clear();
4454 }
4455
4456 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4457 // with cooked pointer data that has the same ids and indices as the raw data.
4458 // The following code can use either the raw or cooked data, as needed.
4459 cookPointerData();
4460
4461 // Apply stylus pressure to current cooked state.
4462 applyExternalStylusTouchState(when);
4463
4464 // Synthesize key down from raw buttons if needed.
4465 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004466 mViewport.displayId, policyFlags,
4467 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004468
4469 // Dispatch the touches either directly or by translation through a pointer on screen.
4470 if (mDeviceMode == DEVICE_MODE_POINTER) {
4471 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4472 !idBits.isEmpty(); ) {
4473 uint32_t id = idBits.clearFirstMarkedBit();
4474 const RawPointerData::Pointer& pointer =
4475 mCurrentRawState.rawPointerData.pointerForId(id);
4476 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4477 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4478 mCurrentCookedState.stylusIdBits.markBit(id);
4479 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4480 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4481 mCurrentCookedState.fingerIdBits.markBit(id);
4482 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4483 mCurrentCookedState.mouseIdBits.markBit(id);
4484 }
4485 }
4486 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
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 }
4495 }
4496
4497 // Stylus takes precedence over all tools, then mouse, then finger.
4498 PointerUsage pointerUsage = mPointerUsage;
4499 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4500 mCurrentCookedState.mouseIdBits.clear();
4501 mCurrentCookedState.fingerIdBits.clear();
4502 pointerUsage = POINTER_USAGE_STYLUS;
4503 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4504 mCurrentCookedState.fingerIdBits.clear();
4505 pointerUsage = POINTER_USAGE_MOUSE;
4506 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4507 isPointerDown(mCurrentRawState.buttonState)) {
4508 pointerUsage = POINTER_USAGE_GESTURES;
4509 }
4510
4511 dispatchPointerUsage(when, policyFlags, pointerUsage);
4512 } else {
4513 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004514 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004515 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4516 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4517
4518 mPointerController->setButtonState(mCurrentRawState.buttonState);
4519 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4520 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004521 mCurrentCookedState.cookedPointerData.touchingIdBits,
4522 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004523 }
4524
Michael Wright8e812822015-06-22 16:18:21 +01004525 if (!mCurrentMotionAborted) {
4526 dispatchButtonRelease(when, policyFlags);
4527 dispatchHoverExit(when, policyFlags);
4528 dispatchTouches(when, policyFlags);
4529 dispatchHoverEnterAndMove(when, policyFlags);
4530 dispatchButtonPress(when, policyFlags);
4531 }
4532
4533 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4534 mCurrentMotionAborted = false;
4535 }
Michael Wright842500e2015-03-13 17:32:02 -07004536 }
4537
4538 // Synthesize key up from raw buttons if needed.
4539 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004540 mViewport.displayId, policyFlags,
4541 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004542
4543 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004544 mCurrentRawState.rawVScroll = 0;
4545 mCurrentRawState.rawHScroll = 0;
4546
4547 // Copy current touch to last touch in preparation for the next cycle.
4548 mLastRawState.copyFrom(mCurrentRawState);
4549 mLastCookedState.copyFrom(mCurrentCookedState);
4550}
4551
4552void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004553 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004554 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4555 }
4556}
4557
4558void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004559 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4560 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004561
Michael Wright53dca3a2015-04-23 17:39:53 +01004562 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4563 float pressure = mExternalStylusState.pressure;
4564 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4565 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4566 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4567 }
4568 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4569 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4570
4571 PointerProperties& properties =
4572 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004573 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4574 properties.toolType = mExternalStylusState.toolType;
4575 }
4576 }
4577}
4578
4579bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4580 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4581 return false;
4582 }
4583
4584 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4585 && state.rawPointerData.pointerCount != 0;
4586 if (initialDown) {
4587 if (mExternalStylusState.pressure != 0.0f) {
4588#if DEBUG_STYLUS_FUSION
4589 ALOGD("Have both stylus and touch data, beginning fusion");
4590#endif
4591 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4592 } else if (timeout) {
4593#if DEBUG_STYLUS_FUSION
4594 ALOGD("Timeout expired, assuming touch is not a stylus.");
4595#endif
4596 resetExternalStylus();
4597 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004598 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4599 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004600 }
4601#if DEBUG_STYLUS_FUSION
4602 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004603 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004604#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004605 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004606 return true;
4607 }
4608 }
4609
4610 // Check if the stylus pointer has gone up.
4611 if (mExternalStylusId != -1 &&
4612 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4613#if DEBUG_STYLUS_FUSION
4614 ALOGD("Stylus pointer is going up");
4615#endif
4616 mExternalStylusId = -1;
4617 }
4618
4619 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004620}
4621
4622void TouchInputMapper::timeoutExpired(nsecs_t when) {
4623 if (mDeviceMode == DEVICE_MODE_POINTER) {
4624 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4625 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4626 }
Michael Wright842500e2015-03-13 17:32:02 -07004627 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004628 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004629 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004630 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4631 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004632 }
4633 }
4634}
4635
4636void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004637 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004638 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004639 // We're either in the middle of a fused stream of data or we're waiting on data before
4640 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4641 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004642 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004643 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004644 }
4645}
4646
4647bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4648 // Check for release of a virtual key.
4649 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004650 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 // Pointer went up while virtual key was down.
4652 mCurrentVirtualKey.down = false;
4653 if (!mCurrentVirtualKey.ignored) {
4654#if DEBUG_VIRTUAL_KEYS
4655 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4656 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4657#endif
4658 dispatchVirtualKey(when, policyFlags,
4659 AKEY_EVENT_ACTION_UP,
4660 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4661 }
4662 return true;
4663 }
4664
Michael Wright842500e2015-03-13 17:32:02 -07004665 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4666 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4667 const RawPointerData::Pointer& pointer =
4668 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004669 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4670 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4671 // Pointer is still within the space of the virtual key.
4672 return true;
4673 }
4674 }
4675
4676 // Pointer left virtual key area or another pointer also went down.
4677 // Send key cancellation but do not consume the touch yet.
4678 // This is useful when the user swipes through from the virtual key area
4679 // into the main display surface.
4680 mCurrentVirtualKey.down = false;
4681 if (!mCurrentVirtualKey.ignored) {
4682#if DEBUG_VIRTUAL_KEYS
4683 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4684 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4685#endif
4686 dispatchVirtualKey(when, policyFlags,
4687 AKEY_EVENT_ACTION_UP,
4688 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4689 | AKEY_EVENT_FLAG_CANCELED);
4690 }
4691 }
4692
Michael Wright842500e2015-03-13 17:32:02 -07004693 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4694 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004696 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4697 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004698 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4699 // If exactly one pointer went down, check for virtual key hit.
4700 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004701 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4703 if (virtualKey) {
4704 mCurrentVirtualKey.down = true;
4705 mCurrentVirtualKey.downTime = when;
4706 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4707 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4708 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4709 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4710
4711 if (!mCurrentVirtualKey.ignored) {
4712#if DEBUG_VIRTUAL_KEYS
4713 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4714 mCurrentVirtualKey.keyCode,
4715 mCurrentVirtualKey.scanCode);
4716#endif
4717 dispatchVirtualKey(when, policyFlags,
4718 AKEY_EVENT_ACTION_DOWN,
4719 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4720 }
4721 }
4722 }
4723 return true;
4724 }
4725 }
4726
4727 // Disable all virtual key touches that happen within a short time interval of the
4728 // most recent touch within the screen area. The idea is to filter out stray
4729 // virtual key presses when interacting with the touch screen.
4730 //
4731 // Problems we're trying to solve:
4732 //
4733 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4734 // virtual key area that is implemented by a separate touch panel and accidentally
4735 // triggers a virtual key.
4736 //
4737 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4738 // area and accidentally triggers a virtual key. This often happens when virtual keys
4739 // are layed out below the screen near to where the on screen keyboard's space bar
4740 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004741 if (mConfig.virtualKeyQuietTime > 0 &&
4742 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4744 }
4745 return false;
4746}
4747
4748void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4749 int32_t keyEventAction, int32_t keyEventFlags) {
4750 int32_t keyCode = mCurrentVirtualKey.keyCode;
4751 int32_t scanCode = mCurrentVirtualKey.scanCode;
4752 nsecs_t downTime = mCurrentVirtualKey.downTime;
4753 int32_t metaState = mContext->getGlobalMetaState();
4754 policyFlags |= POLICY_FLAG_VIRTUAL;
4755
Prabir Pradhan42611e02018-11-27 14:04:02 -08004756 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4757 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004758 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004759 getListener()->notifyKey(&args);
4760}
4761
Michael Wright8e812822015-06-22 16:18:21 +01004762void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4763 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4764 if (!currentIdBits.isEmpty()) {
4765 int32_t metaState = getContext()->getGlobalMetaState();
4766 int32_t buttonState = mCurrentCookedState.buttonState;
4767 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4768 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004769 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004770 mCurrentCookedState.cookedPointerData.pointerProperties,
4771 mCurrentCookedState.cookedPointerData.pointerCoords,
4772 mCurrentCookedState.cookedPointerData.idToIndex,
4773 currentIdBits, -1,
4774 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4775 mCurrentMotionAborted = true;
4776 }
4777}
4778
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004780 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4781 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004782 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004783 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784
4785 if (currentIdBits == lastIdBits) {
4786 if (!currentIdBits.isEmpty()) {
4787 // No pointer id changes so this is a move event.
4788 // The listener takes care of batching moves so we don't have to deal with that here.
4789 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004790 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004792 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004793 mCurrentCookedState.cookedPointerData.pointerProperties,
4794 mCurrentCookedState.cookedPointerData.pointerCoords,
4795 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 currentIdBits, -1,
4797 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4798 }
4799 } else {
4800 // There may be pointers going up and pointers going down and pointers moving
4801 // all at the same time.
4802 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4803 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4804 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4805 BitSet32 dispatchedIdBits(lastIdBits.value);
4806
4807 // Update last coordinates of pointers that have moved so that we observe the new
4808 // pointer positions at the same time as other pointers that have just gone up.
4809 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004810 mCurrentCookedState.cookedPointerData.pointerProperties,
4811 mCurrentCookedState.cookedPointerData.pointerCoords,
4812 mCurrentCookedState.cookedPointerData.idToIndex,
4813 mLastCookedState.cookedPointerData.pointerProperties,
4814 mLastCookedState.cookedPointerData.pointerCoords,
4815 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004817 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 moveNeeded = true;
4819 }
4820
4821 // Dispatch pointer up events.
4822 while (!upIdBits.isEmpty()) {
4823 uint32_t upId = upIdBits.clearFirstMarkedBit();
4824
4825 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004826 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004827 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004828 mLastCookedState.cookedPointerData.pointerProperties,
4829 mLastCookedState.cookedPointerData.pointerCoords,
4830 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004831 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004832 dispatchedIdBits.clearBit(upId);
4833 }
4834
4835 // Dispatch move events if any of the remaining pointers moved from their old locations.
4836 // Although applications receive new locations as part of individual pointer up
4837 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004838 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4840 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004841 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004842 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004843 mCurrentCookedState.cookedPointerData.pointerProperties,
4844 mCurrentCookedState.cookedPointerData.pointerCoords,
4845 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004846 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 }
4848
4849 // Dispatch pointer down events using the new pointer locations.
4850 while (!downIdBits.isEmpty()) {
4851 uint32_t downId = downIdBits.clearFirstMarkedBit();
4852 dispatchedIdBits.markBit(downId);
4853
4854 if (dispatchedIdBits.count() == 1) {
4855 // First pointer is going down. Set down time.
4856 mDownTime = when;
4857 }
4858
4859 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004860 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004861 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004862 mCurrentCookedState.cookedPointerData.pointerProperties,
4863 mCurrentCookedState.cookedPointerData.pointerCoords,
4864 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004865 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004866 }
4867 }
4868}
4869
4870void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4871 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004872 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4873 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004874 int32_t metaState = getContext()->getGlobalMetaState();
4875 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004876 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004877 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004878 mLastCookedState.cookedPointerData.pointerProperties,
4879 mLastCookedState.cookedPointerData.pointerCoords,
4880 mLastCookedState.cookedPointerData.idToIndex,
4881 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4883 mSentHoverEnter = false;
4884 }
4885}
4886
4887void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004888 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4889 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 int32_t metaState = getContext()->getGlobalMetaState();
4891 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004892 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004893 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004894 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004895 mCurrentCookedState.cookedPointerData.pointerProperties,
4896 mCurrentCookedState.cookedPointerData.pointerCoords,
4897 mCurrentCookedState.cookedPointerData.idToIndex,
4898 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4900 mSentHoverEnter = true;
4901 }
4902
4903 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004904 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004905 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004906 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004907 mCurrentCookedState.cookedPointerData.pointerProperties,
4908 mCurrentCookedState.cookedPointerData.pointerCoords,
4909 mCurrentCookedState.cookedPointerData.idToIndex,
4910 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4912 }
4913}
4914
Michael Wright7b159c92015-05-14 14:48:03 +01004915void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4916 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4917 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4918 const int32_t metaState = getContext()->getGlobalMetaState();
4919 int32_t buttonState = mLastCookedState.buttonState;
4920 while (!releasedButtons.isEmpty()) {
4921 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4922 buttonState &= ~actionButton;
4923 dispatchMotion(when, policyFlags, mSource,
4924 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4925 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004926 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004927 mCurrentCookedState.cookedPointerData.pointerProperties,
4928 mCurrentCookedState.cookedPointerData.pointerCoords,
4929 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4930 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4931 }
4932}
4933
4934void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4935 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4936 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4937 const int32_t metaState = getContext()->getGlobalMetaState();
4938 int32_t buttonState = mLastCookedState.buttonState;
4939 while (!pressedButtons.isEmpty()) {
4940 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4941 buttonState |= actionButton;
4942 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4943 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004944 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004945 mCurrentCookedState.cookedPointerData.pointerProperties,
4946 mCurrentCookedState.cookedPointerData.pointerCoords,
4947 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4948 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4949 }
4950}
4951
4952const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4953 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4954 return cookedPointerData.touchingIdBits;
4955 }
4956 return cookedPointerData.hoveringIdBits;
4957}
4958
Michael Wrightd02c5b62014-02-10 15:10:22 -08004959void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004960 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961
Michael Wright842500e2015-03-13 17:32:02 -07004962 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004963 mCurrentCookedState.deviceTimestamp =
4964 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004965 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4966 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4967 mCurrentRawState.rawPointerData.hoveringIdBits;
4968 mCurrentCookedState.cookedPointerData.touchingIdBits =
4969 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970
Michael Wright7b159c92015-05-14 14:48:03 +01004971 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4972 mCurrentCookedState.buttonState = 0;
4973 } else {
4974 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4975 }
4976
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 // Walk through the the active pointers and map device coordinates onto
4978 // surface coordinates and adjust for display orientation.
4979 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004980 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981
4982 // Size
4983 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4984 switch (mCalibration.sizeCalibration) {
4985 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4986 case Calibration::SIZE_CALIBRATION_DIAMETER:
4987 case Calibration::SIZE_CALIBRATION_BOX:
4988 case Calibration::SIZE_CALIBRATION_AREA:
4989 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4990 touchMajor = in.touchMajor;
4991 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4992 toolMajor = in.toolMajor;
4993 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4994 size = mRawPointerAxes.touchMinor.valid
4995 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4996 } else if (mRawPointerAxes.touchMajor.valid) {
4997 toolMajor = touchMajor = in.touchMajor;
4998 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4999 ? in.touchMinor : in.touchMajor;
5000 size = mRawPointerAxes.touchMinor.valid
5001 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5002 } else if (mRawPointerAxes.toolMajor.valid) {
5003 touchMajor = toolMajor = in.toolMajor;
5004 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5005 ? in.toolMinor : in.toolMajor;
5006 size = mRawPointerAxes.toolMinor.valid
5007 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5008 } else {
5009 ALOG_ASSERT(false, "No touch or tool axes. "
5010 "Size calibration should have been resolved to NONE.");
5011 touchMajor = 0;
5012 touchMinor = 0;
5013 toolMajor = 0;
5014 toolMinor = 0;
5015 size = 0;
5016 }
5017
5018 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005019 uint32_t touchingCount =
5020 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 if (touchingCount > 1) {
5022 touchMajor /= touchingCount;
5023 touchMinor /= touchingCount;
5024 toolMajor /= touchingCount;
5025 toolMinor /= touchingCount;
5026 size /= touchingCount;
5027 }
5028 }
5029
5030 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5031 touchMajor *= mGeometricScale;
5032 touchMinor *= mGeometricScale;
5033 toolMajor *= mGeometricScale;
5034 toolMinor *= mGeometricScale;
5035 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5036 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5037 touchMinor = touchMajor;
5038 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5039 toolMinor = toolMajor;
5040 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5041 touchMinor = touchMajor;
5042 toolMinor = toolMajor;
5043 }
5044
5045 mCalibration.applySizeScaleAndBias(&touchMajor);
5046 mCalibration.applySizeScaleAndBias(&touchMinor);
5047 mCalibration.applySizeScaleAndBias(&toolMajor);
5048 mCalibration.applySizeScaleAndBias(&toolMinor);
5049 size *= mSizeScale;
5050 break;
5051 default:
5052 touchMajor = 0;
5053 touchMinor = 0;
5054 toolMajor = 0;
5055 toolMinor = 0;
5056 size = 0;
5057 break;
5058 }
5059
5060 // Pressure
5061 float pressure;
5062 switch (mCalibration.pressureCalibration) {
5063 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5064 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5065 pressure = in.pressure * mPressureScale;
5066 break;
5067 default:
5068 pressure = in.isHovering ? 0 : 1;
5069 break;
5070 }
5071
5072 // Tilt and Orientation
5073 float tilt;
5074 float orientation;
5075 if (mHaveTilt) {
5076 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5077 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5078 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5079 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5080 } else {
5081 tilt = 0;
5082
5083 switch (mCalibration.orientationCalibration) {
5084 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5085 orientation = in.orientation * mOrientationScale;
5086 break;
5087 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5088 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5089 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5090 if (c1 != 0 || c2 != 0) {
5091 orientation = atan2f(c1, c2) * 0.5f;
5092 float confidence = hypotf(c1, c2);
5093 float scale = 1.0f + confidence / 16.0f;
5094 touchMajor *= scale;
5095 touchMinor /= scale;
5096 toolMajor *= scale;
5097 toolMinor /= scale;
5098 } else {
5099 orientation = 0;
5100 }
5101 break;
5102 }
5103 default:
5104 orientation = 0;
5105 }
5106 }
5107
5108 // Distance
5109 float distance;
5110 switch (mCalibration.distanceCalibration) {
5111 case Calibration::DISTANCE_CALIBRATION_SCALED:
5112 distance = in.distance * mDistanceScale;
5113 break;
5114 default:
5115 distance = 0;
5116 }
5117
5118 // Coverage
5119 int32_t rawLeft, rawTop, rawRight, rawBottom;
5120 switch (mCalibration.coverageCalibration) {
5121 case Calibration::COVERAGE_CALIBRATION_BOX:
5122 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5123 rawRight = in.toolMinor & 0x0000ffff;
5124 rawBottom = in.toolMajor & 0x0000ffff;
5125 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5126 break;
5127 default:
5128 rawLeft = rawTop = rawRight = rawBottom = 0;
5129 break;
5130 }
5131
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005132 // Adjust X,Y coords for device calibration
5133 // TODO: Adjust coverage coords?
5134 float xTransformed = in.x, yTransformed = in.y;
5135 mAffineTransform.applyTo(xTransformed, yTransformed);
5136
5137 // Adjust X, Y, and coverage coords for surface orientation.
5138 float x, y;
5139 float left, top, right, bottom;
5140
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 switch (mSurfaceOrientation) {
5142 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005143 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5144 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5146 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5147 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5148 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5149 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005150 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5152 }
5153 break;
5154 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005155 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005156 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005157 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5158 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5160 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5161 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005162 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5164 }
5165 break;
5166 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005167 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005168 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005169 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5170 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5172 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5173 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005174 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5176 }
5177 break;
5178 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005179 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5180 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5182 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5183 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5184 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5185 break;
5186 }
5187
5188 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005189 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 out.clear();
5191 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5192 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5194 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5195 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5196 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5197 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5198 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5199 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5200 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5201 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5202 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5203 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5204 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5205 } else {
5206 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5207 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5208 }
5209
5210 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005211 PointerProperties& properties =
5212 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 uint32_t id = in.id;
5214 properties.clear();
5215 properties.id = id;
5216 properties.toolType = in.toolType;
5217
5218 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005219 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 }
5221}
5222
5223void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5224 PointerUsage pointerUsage) {
5225 if (pointerUsage != mPointerUsage) {
5226 abortPointerUsage(when, policyFlags);
5227 mPointerUsage = pointerUsage;
5228 }
5229
5230 switch (mPointerUsage) {
5231 case POINTER_USAGE_GESTURES:
5232 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5233 break;
5234 case POINTER_USAGE_STYLUS:
5235 dispatchPointerStylus(when, policyFlags);
5236 break;
5237 case POINTER_USAGE_MOUSE:
5238 dispatchPointerMouse(when, policyFlags);
5239 break;
5240 default:
5241 break;
5242 }
5243}
5244
5245void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5246 switch (mPointerUsage) {
5247 case POINTER_USAGE_GESTURES:
5248 abortPointerGestures(when, policyFlags);
5249 break;
5250 case POINTER_USAGE_STYLUS:
5251 abortPointerStylus(when, policyFlags);
5252 break;
5253 case POINTER_USAGE_MOUSE:
5254 abortPointerMouse(when, policyFlags);
5255 break;
5256 default:
5257 break;
5258 }
5259
5260 mPointerUsage = POINTER_USAGE_NONE;
5261}
5262
5263void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5264 bool isTimeout) {
5265 // Update current gesture coordinates.
5266 bool cancelPreviousGesture, finishPreviousGesture;
5267 bool sendEvents = preparePointerGestures(when,
5268 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5269 if (!sendEvents) {
5270 return;
5271 }
5272 if (finishPreviousGesture) {
5273 cancelPreviousGesture = false;
5274 }
5275
5276 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005277 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5278 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 if (finishPreviousGesture || cancelPreviousGesture) {
5280 mPointerController->clearSpots();
5281 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005282
5283 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5284 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5285 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005286 mPointerGesture.currentGestureIdBits,
5287 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 } else {
5290 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5291 }
5292
5293 // Show or hide the pointer if needed.
5294 switch (mPointerGesture.currentGestureMode) {
5295 case PointerGesture::NEUTRAL:
5296 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005297 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5298 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 // Remind the user of where the pointer is after finishing a gesture with spots.
5300 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5301 }
5302 break;
5303 case PointerGesture::TAP:
5304 case PointerGesture::TAP_DRAG:
5305 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5306 case PointerGesture::HOVER:
5307 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005308 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 // Unfade the pointer when the current gesture manipulates the
5310 // area directly under the pointer.
5311 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5312 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 case PointerGesture::FREEFORM:
5314 // Fade the pointer when the current gesture manipulates a different
5315 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005316 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5318 } else {
5319 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5320 }
5321 break;
5322 }
5323
5324 // Send events!
5325 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005326 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327
5328 // Update last coordinates of pointers that have moved so that we observe the new
5329 // pointer positions at the same time as other pointers that have just gone up.
5330 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5331 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5332 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5333 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5334 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5335 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5336 bool moveNeeded = false;
5337 if (down && !cancelPreviousGesture && !finishPreviousGesture
5338 && !mPointerGesture.lastGestureIdBits.isEmpty()
5339 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5340 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5341 & mPointerGesture.lastGestureIdBits.value);
5342 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5343 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5344 mPointerGesture.lastGestureProperties,
5345 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5346 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005347 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 moveNeeded = true;
5349 }
5350 }
5351
5352 // Send motion events for all pointers that went up or were canceled.
5353 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5354 if (!dispatchedGestureIdBits.isEmpty()) {
5355 if (cancelPreviousGesture) {
5356 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005357 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005358 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 mPointerGesture.lastGestureProperties,
5360 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005361 dispatchedGestureIdBits, -1, 0,
5362 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363
5364 dispatchedGestureIdBits.clear();
5365 } else {
5366 BitSet32 upGestureIdBits;
5367 if (finishPreviousGesture) {
5368 upGestureIdBits = dispatchedGestureIdBits;
5369 } else {
5370 upGestureIdBits.value = dispatchedGestureIdBits.value
5371 & ~mPointerGesture.currentGestureIdBits.value;
5372 }
5373 while (!upGestureIdBits.isEmpty()) {
5374 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5375
5376 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005377 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005379 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 mPointerGesture.lastGestureProperties,
5381 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5382 dispatchedGestureIdBits, id,
5383 0, 0, mPointerGesture.downTime);
5384
5385 dispatchedGestureIdBits.clearBit(id);
5386 }
5387 }
5388 }
5389
5390 // Send motion events for all pointers that moved.
5391 if (moveNeeded) {
5392 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005393 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005394 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 mPointerGesture.currentGestureProperties,
5396 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5397 dispatchedGestureIdBits, -1,
5398 0, 0, mPointerGesture.downTime);
5399 }
5400
5401 // Send motion events for all pointers that went down.
5402 if (down) {
5403 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5404 & ~dispatchedGestureIdBits.value);
5405 while (!downGestureIdBits.isEmpty()) {
5406 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5407 dispatchedGestureIdBits.markBit(id);
5408
5409 if (dispatchedGestureIdBits.count() == 1) {
5410 mPointerGesture.downTime = when;
5411 }
5412
5413 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005414 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005415 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005416 mPointerGesture.currentGestureProperties,
5417 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5418 dispatchedGestureIdBits, id,
5419 0, 0, mPointerGesture.downTime);
5420 }
5421 }
5422
5423 // Send motion events for hover.
5424 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5425 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005426 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005427 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005428 mPointerGesture.currentGestureProperties,
5429 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5430 mPointerGesture.currentGestureIdBits, -1,
5431 0, 0, mPointerGesture.downTime);
5432 } else if (dispatchedGestureIdBits.isEmpty()
5433 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5434 // Synthesize a hover move event after all pointers go up to indicate that
5435 // the pointer is hovering again even if the user is not currently touching
5436 // the touch pad. This ensures that a view will receive a fresh hover enter
5437 // event after a tap.
5438 float x, y;
5439 mPointerController->getPosition(&x, &y);
5440
5441 PointerProperties pointerProperties;
5442 pointerProperties.clear();
5443 pointerProperties.id = 0;
5444 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5445
5446 PointerCoords pointerCoords;
5447 pointerCoords.clear();
5448 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5449 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5450
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005451 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005452 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005453 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005454 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005455 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005456 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005457 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 getListener()->notifyMotion(&args);
5459 }
5460
5461 // Update state.
5462 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5463 if (!down) {
5464 mPointerGesture.lastGestureIdBits.clear();
5465 } else {
5466 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5467 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5468 uint32_t id = idBits.clearFirstMarkedBit();
5469 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5470 mPointerGesture.lastGestureProperties[index].copyFrom(
5471 mPointerGesture.currentGestureProperties[index]);
5472 mPointerGesture.lastGestureCoords[index].copyFrom(
5473 mPointerGesture.currentGestureCoords[index]);
5474 mPointerGesture.lastGestureIdToIndex[id] = index;
5475 }
5476 }
5477}
5478
5479void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5480 // Cancel previously dispatches pointers.
5481 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5482 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005483 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005485 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005486 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005487 mPointerGesture.lastGestureProperties,
5488 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5489 mPointerGesture.lastGestureIdBits, -1,
5490 0, 0, mPointerGesture.downTime);
5491 }
5492
5493 // Reset the current pointer gesture.
5494 mPointerGesture.reset();
5495 mPointerVelocityControl.reset();
5496
5497 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005498 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005499 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5500 mPointerController->clearSpots();
5501 }
5502}
5503
5504bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5505 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5506 *outCancelPreviousGesture = false;
5507 *outFinishPreviousGesture = false;
5508
5509 // Handle TAP timeout.
5510 if (isTimeout) {
5511#if DEBUG_GESTURES
5512 ALOGD("Gestures: Processing timeout");
5513#endif
5514
5515 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5516 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5517 // The tap/drag timeout has not yet expired.
5518 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5519 + mConfig.pointerGestureTapDragInterval);
5520 } else {
5521 // The tap is finished.
5522#if DEBUG_GESTURES
5523 ALOGD("Gestures: TAP finished");
5524#endif
5525 *outFinishPreviousGesture = true;
5526
5527 mPointerGesture.activeGestureId = -1;
5528 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5529 mPointerGesture.currentGestureIdBits.clear();
5530
5531 mPointerVelocityControl.reset();
5532 return true;
5533 }
5534 }
5535
5536 // We did not handle this timeout.
5537 return false;
5538 }
5539
Michael Wright842500e2015-03-13 17:32:02 -07005540 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5541 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542
5543 // Update the velocity tracker.
5544 {
5545 VelocityTracker::Position positions[MAX_POINTERS];
5546 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005547 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005549 const RawPointerData::Pointer& pointer =
5550 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005551 positions[count].x = pointer.x * mPointerXMovementScale;
5552 positions[count].y = pointer.y * mPointerYMovementScale;
5553 }
5554 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005555 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 }
5557
5558 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5559 // to NEUTRAL, then we should not generate tap event.
5560 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5561 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5562 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5563 mPointerGesture.resetTap();
5564 }
5565
5566 // Pick a new active touch id if needed.
5567 // Choose an arbitrary pointer that just went down, if there is one.
5568 // Otherwise choose an arbitrary remaining pointer.
5569 // This guarantees we always have an active touch id when there is at least one pointer.
5570 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5572 int32_t activeTouchId = lastActiveTouchId;
5573 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005574 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005576 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577 mPointerGesture.firstTouchTime = when;
5578 }
Michael Wright842500e2015-03-13 17:32:02 -07005579 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005580 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005582 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 } else {
5584 activeTouchId = mPointerGesture.activeTouchId = -1;
5585 }
5586 }
5587
5588 // Determine whether we are in quiet time.
5589 bool isQuietTime = false;
5590 if (activeTouchId < 0) {
5591 mPointerGesture.resetQuietTime();
5592 } else {
5593 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5594 if (!isQuietTime) {
5595 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5596 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5597 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5598 && currentFingerCount < 2) {
5599 // Enter quiet time when exiting swipe or freeform state.
5600 // This is to prevent accidentally entering the hover state and flinging the
5601 // pointer when finishing a swipe and there is still one pointer left onscreen.
5602 isQuietTime = true;
5603 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5604 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005605 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005606 // Enter quiet time when releasing the button and there are still two or more
5607 // fingers down. This may indicate that one finger was used to press the button
5608 // but it has not gone up yet.
5609 isQuietTime = true;
5610 }
5611 if (isQuietTime) {
5612 mPointerGesture.quietTime = when;
5613 }
5614 }
5615 }
5616
5617 // Switch states based on button and pointer state.
5618 if (isQuietTime) {
5619 // Case 1: Quiet time. (QUIET)
5620#if DEBUG_GESTURES
5621 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5622 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5623#endif
5624 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5625 *outFinishPreviousGesture = true;
5626 }
5627
5628 mPointerGesture.activeGestureId = -1;
5629 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5630 mPointerGesture.currentGestureIdBits.clear();
5631
5632 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005633 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5635 // The pointer follows the active touch point.
5636 // Emit DOWN, MOVE, UP events at the pointer location.
5637 //
5638 // Only the active touch matters; other fingers are ignored. This policy helps
5639 // to handle the case where the user places a second finger on the touch pad
5640 // to apply the necessary force to depress an integrated button below the surface.
5641 // We don't want the second finger to be delivered to applications.
5642 //
5643 // For this to work well, we need to make sure to track the pointer that is really
5644 // active. If the user first puts one finger down to click then adds another
5645 // finger to drag then the active pointer should switch to the finger that is
5646 // being dragged.
5647#if DEBUG_GESTURES
5648 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5649 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5650#endif
5651 // Reset state when just starting.
5652 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5653 *outFinishPreviousGesture = true;
5654 mPointerGesture.activeGestureId = 0;
5655 }
5656
5657 // Switch pointers if needed.
5658 // Find the fastest pointer and follow it.
5659 if (activeTouchId >= 0 && currentFingerCount > 1) {
5660 int32_t bestId = -1;
5661 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005662 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005663 uint32_t id = idBits.clearFirstMarkedBit();
5664 float vx, vy;
5665 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5666 float speed = hypotf(vx, vy);
5667 if (speed > bestSpeed) {
5668 bestId = id;
5669 bestSpeed = speed;
5670 }
5671 }
5672 }
5673 if (bestId >= 0 && bestId != activeTouchId) {
5674 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675#if DEBUG_GESTURES
5676 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5677 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5678#endif
5679 }
5680 }
5681
Jun Mukaifa1706a2015-12-03 01:14:46 -08005682 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005683 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005684 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005685 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005686 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005687 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005688 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5689 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690
5691 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5692 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5693
5694 // Move the pointer using a relative motion.
5695 // When using spots, the click will occur at the position of the anchor
5696 // spot and all other spots will move there.
5697 mPointerController->move(deltaX, deltaY);
5698 } else {
5699 mPointerVelocityControl.reset();
5700 }
5701
5702 float x, y;
5703 mPointerController->getPosition(&x, &y);
5704
5705 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5706 mPointerGesture.currentGestureIdBits.clear();
5707 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5708 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5709 mPointerGesture.currentGestureProperties[0].clear();
5710 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5711 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5712 mPointerGesture.currentGestureCoords[0].clear();
5713 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5714 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5715 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5716 } else if (currentFingerCount == 0) {
5717 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5718 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5719 *outFinishPreviousGesture = true;
5720 }
5721
5722 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5723 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5724 bool tapped = false;
5725 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5726 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5727 && lastFingerCount == 1) {
5728 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5729 float x, y;
5730 mPointerController->getPosition(&x, &y);
5731 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5732 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5733#if DEBUG_GESTURES
5734 ALOGD("Gestures: TAP");
5735#endif
5736
5737 mPointerGesture.tapUpTime = when;
5738 getContext()->requestTimeoutAtTime(when
5739 + mConfig.pointerGestureTapDragInterval);
5740
5741 mPointerGesture.activeGestureId = 0;
5742 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5743 mPointerGesture.currentGestureIdBits.clear();
5744 mPointerGesture.currentGestureIdBits.markBit(
5745 mPointerGesture.activeGestureId);
5746 mPointerGesture.currentGestureIdToIndex[
5747 mPointerGesture.activeGestureId] = 0;
5748 mPointerGesture.currentGestureProperties[0].clear();
5749 mPointerGesture.currentGestureProperties[0].id =
5750 mPointerGesture.activeGestureId;
5751 mPointerGesture.currentGestureProperties[0].toolType =
5752 AMOTION_EVENT_TOOL_TYPE_FINGER;
5753 mPointerGesture.currentGestureCoords[0].clear();
5754 mPointerGesture.currentGestureCoords[0].setAxisValue(
5755 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5756 mPointerGesture.currentGestureCoords[0].setAxisValue(
5757 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5758 mPointerGesture.currentGestureCoords[0].setAxisValue(
5759 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5760
5761 tapped = true;
5762 } else {
5763#if DEBUG_GESTURES
5764 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5765 x - mPointerGesture.tapX,
5766 y - mPointerGesture.tapY);
5767#endif
5768 }
5769 } else {
5770#if DEBUG_GESTURES
5771 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5772 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5773 (when - mPointerGesture.tapDownTime) * 0.000001f);
5774 } else {
5775 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5776 }
5777#endif
5778 }
5779 }
5780
5781 mPointerVelocityControl.reset();
5782
5783 if (!tapped) {
5784#if DEBUG_GESTURES
5785 ALOGD("Gestures: NEUTRAL");
5786#endif
5787 mPointerGesture.activeGestureId = -1;
5788 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5789 mPointerGesture.currentGestureIdBits.clear();
5790 }
5791 } else if (currentFingerCount == 1) {
5792 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5793 // The pointer follows the active touch point.
5794 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5795 // When in TAP_DRAG, emit MOVE events at the pointer location.
5796 ALOG_ASSERT(activeTouchId >= 0);
5797
5798 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5799 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5800 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5801 float x, y;
5802 mPointerController->getPosition(&x, &y);
5803 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5804 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5805 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5806 } else {
5807#if DEBUG_GESTURES
5808 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5809 x - mPointerGesture.tapX,
5810 y - mPointerGesture.tapY);
5811#endif
5812 }
5813 } else {
5814#if DEBUG_GESTURES
5815 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5816 (when - mPointerGesture.tapUpTime) * 0.000001f);
5817#endif
5818 }
5819 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5820 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5821 }
5822
Jun Mukaifa1706a2015-12-03 01:14:46 -08005823 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005824 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005825 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005826 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005827 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005828 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005829 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5830 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831
5832 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5833 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5834
5835 // Move the pointer using a relative motion.
5836 // When using spots, the hover or drag will occur at the position of the anchor spot.
5837 mPointerController->move(deltaX, deltaY);
5838 } else {
5839 mPointerVelocityControl.reset();
5840 }
5841
5842 bool down;
5843 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5844#if DEBUG_GESTURES
5845 ALOGD("Gestures: TAP_DRAG");
5846#endif
5847 down = true;
5848 } else {
5849#if DEBUG_GESTURES
5850 ALOGD("Gestures: HOVER");
5851#endif
5852 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5853 *outFinishPreviousGesture = true;
5854 }
5855 mPointerGesture.activeGestureId = 0;
5856 down = false;
5857 }
5858
5859 float x, y;
5860 mPointerController->getPosition(&x, &y);
5861
5862 mPointerGesture.currentGestureIdBits.clear();
5863 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5864 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5865 mPointerGesture.currentGestureProperties[0].clear();
5866 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5867 mPointerGesture.currentGestureProperties[0].toolType =
5868 AMOTION_EVENT_TOOL_TYPE_FINGER;
5869 mPointerGesture.currentGestureCoords[0].clear();
5870 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5871 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5872 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5873 down ? 1.0f : 0.0f);
5874
5875 if (lastFingerCount == 0 && currentFingerCount != 0) {
5876 mPointerGesture.resetTap();
5877 mPointerGesture.tapDownTime = when;
5878 mPointerGesture.tapX = x;
5879 mPointerGesture.tapY = y;
5880 }
5881 } else {
5882 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5883 // We need to provide feedback for each finger that goes down so we cannot wait
5884 // for the fingers to move before deciding what to do.
5885 //
5886 // The ambiguous case is deciding what to do when there are two fingers down but they
5887 // have not moved enough to determine whether they are part of a drag or part of a
5888 // freeform gesture, or just a press or long-press at the pointer location.
5889 //
5890 // When there are two fingers we start with the PRESS hypothesis and we generate a
5891 // down at the pointer location.
5892 //
5893 // When the two fingers move enough or when additional fingers are added, we make
5894 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5895 ALOG_ASSERT(activeTouchId >= 0);
5896
5897 bool settled = when >= mPointerGesture.firstTouchTime
5898 + mConfig.pointerGestureMultitouchSettleInterval;
5899 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5900 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5901 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5902 *outFinishPreviousGesture = true;
5903 } else if (!settled && currentFingerCount > lastFingerCount) {
5904 // Additional pointers have gone down but not yet settled.
5905 // Reset the gesture.
5906#if DEBUG_GESTURES
5907 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5908 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5909 + mConfig.pointerGestureMultitouchSettleInterval - when)
5910 * 0.000001f);
5911#endif
5912 *outCancelPreviousGesture = true;
5913 } else {
5914 // Continue previous gesture.
5915 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5916 }
5917
5918 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5919 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5920 mPointerGesture.activeGestureId = 0;
5921 mPointerGesture.referenceIdBits.clear();
5922 mPointerVelocityControl.reset();
5923
5924 // Use the centroid and pointer location as the reference points for the gesture.
5925#if DEBUG_GESTURES
5926 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5927 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5928 + mConfig.pointerGestureMultitouchSettleInterval - when)
5929 * 0.000001f);
5930#endif
Michael Wright842500e2015-03-13 17:32:02 -07005931 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932 &mPointerGesture.referenceTouchX,
5933 &mPointerGesture.referenceTouchY);
5934 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5935 &mPointerGesture.referenceGestureY);
5936 }
5937
5938 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005939 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005940 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5941 uint32_t id = idBits.clearFirstMarkedBit();
5942 mPointerGesture.referenceDeltas[id].dx = 0;
5943 mPointerGesture.referenceDeltas[id].dy = 0;
5944 }
Michael Wright842500e2015-03-13 17:32:02 -07005945 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005946
5947 // Add delta for all fingers and calculate a common movement delta.
5948 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005949 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5950 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005951 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5952 bool first = (idBits == commonIdBits);
5953 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005954 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5955 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005956 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5957 delta.dx += cpd.x - lpd.x;
5958 delta.dy += cpd.y - lpd.y;
5959
5960 if (first) {
5961 commonDeltaX = delta.dx;
5962 commonDeltaY = delta.dy;
5963 } else {
5964 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5965 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5966 }
5967 }
5968
5969 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5970 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5971 float dist[MAX_POINTER_ID + 1];
5972 int32_t distOverThreshold = 0;
5973 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5974 uint32_t id = idBits.clearFirstMarkedBit();
5975 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5976 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5977 delta.dy * mPointerYZoomScale);
5978 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5979 distOverThreshold += 1;
5980 }
5981 }
5982
5983 // Only transition when at least two pointers have moved further than
5984 // the minimum distance threshold.
5985 if (distOverThreshold >= 2) {
5986 if (currentFingerCount > 2) {
5987 // There are more than two pointers, switch to FREEFORM.
5988#if DEBUG_GESTURES
5989 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5990 currentFingerCount);
5991#endif
5992 *outCancelPreviousGesture = true;
5993 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5994 } else {
5995 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005996 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005997 uint32_t id1 = idBits.clearFirstMarkedBit();
5998 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005999 const RawPointerData::Pointer& p1 =
6000 mCurrentRawState.rawPointerData.pointerForId(id1);
6001 const RawPointerData::Pointer& p2 =
6002 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006003 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6004 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6005 // There are two pointers but they are too far apart for a SWIPE,
6006 // switch to FREEFORM.
6007#if DEBUG_GESTURES
6008 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6009 mutualDistance, mPointerGestureMaxSwipeWidth);
6010#endif
6011 *outCancelPreviousGesture = true;
6012 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6013 } else {
6014 // There are two pointers. Wait for both pointers to start moving
6015 // before deciding whether this is a SWIPE or FREEFORM gesture.
6016 float dist1 = dist[id1];
6017 float dist2 = dist[id2];
6018 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6019 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6020 // Calculate the dot product of the displacement vectors.
6021 // When the vectors are oriented in approximately the same direction,
6022 // the angle betweeen them is near zero and the cosine of the angle
6023 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6024 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6025 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6026 float dx1 = delta1.dx * mPointerXZoomScale;
6027 float dy1 = delta1.dy * mPointerYZoomScale;
6028 float dx2 = delta2.dx * mPointerXZoomScale;
6029 float dy2 = delta2.dy * mPointerYZoomScale;
6030 float dot = dx1 * dx2 + dy1 * dy2;
6031 float cosine = dot / (dist1 * dist2); // denominator always > 0
6032 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6033 // Pointers are moving in the same direction. Switch to SWIPE.
6034#if DEBUG_GESTURES
6035 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6036 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6037 "cosine %0.3f >= %0.3f",
6038 dist1, mConfig.pointerGestureMultitouchMinDistance,
6039 dist2, mConfig.pointerGestureMultitouchMinDistance,
6040 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6041#endif
6042 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6043 } else {
6044 // Pointers are moving in different directions. Switch to FREEFORM.
6045#if DEBUG_GESTURES
6046 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6047 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6048 "cosine %0.3f < %0.3f",
6049 dist1, mConfig.pointerGestureMultitouchMinDistance,
6050 dist2, mConfig.pointerGestureMultitouchMinDistance,
6051 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6052#endif
6053 *outCancelPreviousGesture = true;
6054 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6055 }
6056 }
6057 }
6058 }
6059 }
6060 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6061 // Switch from SWIPE to FREEFORM if additional pointers go down.
6062 // Cancel previous gesture.
6063 if (currentFingerCount > 2) {
6064#if DEBUG_GESTURES
6065 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6066 currentFingerCount);
6067#endif
6068 *outCancelPreviousGesture = true;
6069 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6070 }
6071 }
6072
6073 // Move the reference points based on the overall group motion of the fingers
6074 // except in PRESS mode while waiting for a transition to occur.
6075 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6076 && (commonDeltaX || commonDeltaY)) {
6077 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6078 uint32_t id = idBits.clearFirstMarkedBit();
6079 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6080 delta.dx = 0;
6081 delta.dy = 0;
6082 }
6083
6084 mPointerGesture.referenceTouchX += commonDeltaX;
6085 mPointerGesture.referenceTouchY += commonDeltaY;
6086
6087 commonDeltaX *= mPointerXMovementScale;
6088 commonDeltaY *= mPointerYMovementScale;
6089
6090 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6091 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6092
6093 mPointerGesture.referenceGestureX += commonDeltaX;
6094 mPointerGesture.referenceGestureY += commonDeltaY;
6095 }
6096
6097 // Report gestures.
6098 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6099 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6100 // PRESS or SWIPE mode.
6101#if DEBUG_GESTURES
6102 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6103 "activeGestureId=%d, currentTouchPointerCount=%d",
6104 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6105#endif
6106 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6107
6108 mPointerGesture.currentGestureIdBits.clear();
6109 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6110 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6111 mPointerGesture.currentGestureProperties[0].clear();
6112 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6113 mPointerGesture.currentGestureProperties[0].toolType =
6114 AMOTION_EVENT_TOOL_TYPE_FINGER;
6115 mPointerGesture.currentGestureCoords[0].clear();
6116 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6117 mPointerGesture.referenceGestureX);
6118 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6119 mPointerGesture.referenceGestureY);
6120 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6121 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6122 // FREEFORM mode.
6123#if DEBUG_GESTURES
6124 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6125 "activeGestureId=%d, currentTouchPointerCount=%d",
6126 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6127#endif
6128 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6129
6130 mPointerGesture.currentGestureIdBits.clear();
6131
6132 BitSet32 mappedTouchIdBits;
6133 BitSet32 usedGestureIdBits;
6134 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6135 // Initially, assign the active gesture id to the active touch point
6136 // if there is one. No other touch id bits are mapped yet.
6137 if (!*outCancelPreviousGesture) {
6138 mappedTouchIdBits.markBit(activeTouchId);
6139 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6140 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6141 mPointerGesture.activeGestureId;
6142 } else {
6143 mPointerGesture.activeGestureId = -1;
6144 }
6145 } else {
6146 // Otherwise, assume we mapped all touches from the previous frame.
6147 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006148 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6149 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006150 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6151
6152 // Check whether we need to choose a new active gesture id because the
6153 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006154 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6155 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006156 !upTouchIdBits.isEmpty(); ) {
6157 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6158 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6159 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6160 mPointerGesture.activeGestureId = -1;
6161 break;
6162 }
6163 }
6164 }
6165
6166#if DEBUG_GESTURES
6167 ALOGD("Gestures: FREEFORM follow up "
6168 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6169 "activeGestureId=%d",
6170 mappedTouchIdBits.value, usedGestureIdBits.value,
6171 mPointerGesture.activeGestureId);
6172#endif
6173
Michael Wright842500e2015-03-13 17:32:02 -07006174 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 for (uint32_t i = 0; i < currentFingerCount; i++) {
6176 uint32_t touchId = idBits.clearFirstMarkedBit();
6177 uint32_t gestureId;
6178 if (!mappedTouchIdBits.hasBit(touchId)) {
6179 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6180 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6181#if DEBUG_GESTURES
6182 ALOGD("Gestures: FREEFORM "
6183 "new mapping for touch id %d -> gesture id %d",
6184 touchId, gestureId);
6185#endif
6186 } else {
6187 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6188#if DEBUG_GESTURES
6189 ALOGD("Gestures: FREEFORM "
6190 "existing mapping for touch id %d -> gesture id %d",
6191 touchId, gestureId);
6192#endif
6193 }
6194 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6195 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6196
6197 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006198 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006199 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6200 * mPointerXZoomScale;
6201 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6202 * mPointerYZoomScale;
6203 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6204
6205 mPointerGesture.currentGestureProperties[i].clear();
6206 mPointerGesture.currentGestureProperties[i].id = gestureId;
6207 mPointerGesture.currentGestureProperties[i].toolType =
6208 AMOTION_EVENT_TOOL_TYPE_FINGER;
6209 mPointerGesture.currentGestureCoords[i].clear();
6210 mPointerGesture.currentGestureCoords[i].setAxisValue(
6211 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6212 mPointerGesture.currentGestureCoords[i].setAxisValue(
6213 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6214 mPointerGesture.currentGestureCoords[i].setAxisValue(
6215 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6216 }
6217
6218 if (mPointerGesture.activeGestureId < 0) {
6219 mPointerGesture.activeGestureId =
6220 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6221#if DEBUG_GESTURES
6222 ALOGD("Gestures: FREEFORM new "
6223 "activeGestureId=%d", mPointerGesture.activeGestureId);
6224#endif
6225 }
6226 }
6227 }
6228
Michael Wright842500e2015-03-13 17:32:02 -07006229 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006230
6231#if DEBUG_GESTURES
6232 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6233 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6234 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6235 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6236 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6237 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6238 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6239 uint32_t id = idBits.clearFirstMarkedBit();
6240 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6241 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6242 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6243 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6244 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6245 id, index, properties.toolType,
6246 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6247 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6248 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6249 }
6250 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6251 uint32_t id = idBits.clearFirstMarkedBit();
6252 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6253 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6254 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6255 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6256 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6257 id, index, properties.toolType,
6258 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6259 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6260 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6261 }
6262#endif
6263 return true;
6264}
6265
6266void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6267 mPointerSimple.currentCoords.clear();
6268 mPointerSimple.currentProperties.clear();
6269
6270 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006271 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6272 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6273 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6274 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6275 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006276 mPointerController->setPosition(x, y);
6277
Michael Wright842500e2015-03-13 17:32:02 -07006278 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006279 down = !hovering;
6280
6281 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006282 mPointerSimple.currentCoords.copyFrom(
6283 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6285 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6286 mPointerSimple.currentProperties.id = 0;
6287 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006288 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289 } else {
6290 down = false;
6291 hovering = false;
6292 }
6293
6294 dispatchPointerSimple(when, policyFlags, down, hovering);
6295}
6296
6297void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6298 abortPointerSimple(when, policyFlags);
6299}
6300
6301void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6302 mPointerSimple.currentCoords.clear();
6303 mPointerSimple.currentProperties.clear();
6304
6305 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006306 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6307 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6308 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006309 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006310 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6311 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006312 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006313 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006315 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006316 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 * mPointerYMovementScale;
6318
6319 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6320 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6321
6322 mPointerController->move(deltaX, deltaY);
6323 } else {
6324 mPointerVelocityControl.reset();
6325 }
6326
Michael Wright842500e2015-03-13 17:32:02 -07006327 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006328 hovering = !down;
6329
6330 float x, y;
6331 mPointerController->getPosition(&x, &y);
6332 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006333 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6335 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6336 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6337 hovering ? 0.0f : 1.0f);
6338 mPointerSimple.currentProperties.id = 0;
6339 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006340 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006341 } else {
6342 mPointerVelocityControl.reset();
6343
6344 down = false;
6345 hovering = false;
6346 }
6347
6348 dispatchPointerSimple(when, policyFlags, down, hovering);
6349}
6350
6351void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6352 abortPointerSimple(when, policyFlags);
6353
6354 mPointerVelocityControl.reset();
6355}
6356
6357void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6358 bool down, bool hovering) {
6359 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006360 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361
Yi Kong9b14ac62018-07-17 13:48:38 -07006362 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006363 if (down || hovering) {
6364 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6365 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006366 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006367 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6368 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6369 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6370 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006371 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 }
6373
6374 if (mPointerSimple.down && !down) {
6375 mPointerSimple.down = false;
6376
6377 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006378 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006379 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006380 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6381 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006382 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6383 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006384 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006385 getListener()->notifyMotion(&args);
6386 }
6387
6388 if (mPointerSimple.hovering && !hovering) {
6389 mPointerSimple.hovering = false;
6390
6391 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006392 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6393 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006394 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6395 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6397 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006398 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399 getListener()->notifyMotion(&args);
6400 }
6401
6402 if (down) {
6403 if (!mPointerSimple.down) {
6404 mPointerSimple.down = true;
6405 mPointerSimple.downTime = when;
6406
6407 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006408 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6409 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006410 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6411 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006412 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006413 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6414 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006415 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 getListener()->notifyMotion(&args);
6417 }
6418
6419 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006420 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6421 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006422 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6423 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006424 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6425 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006426 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006427 getListener()->notifyMotion(&args);
6428 }
6429
6430 if (hovering) {
6431 if (!mPointerSimple.hovering) {
6432 mPointerSimple.hovering = true;
6433
6434 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006435 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6436 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006437 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006438 mCurrentRawState.buttonState, MotionClassification::NONE,
6439 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6441 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006442 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006443 getListener()->notifyMotion(&args);
6444 }
6445
6446 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006447 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6448 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006449 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006450 mCurrentRawState.buttonState, MotionClassification::NONE,
6451 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006452 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6453 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006454 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006455 getListener()->notifyMotion(&args);
6456 }
6457
Michael Wright842500e2015-03-13 17:32:02 -07006458 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6459 float vscroll = mCurrentRawState.rawVScroll;
6460 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006461 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6462 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463
6464 // Send scroll.
6465 PointerCoords pointerCoords;
6466 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6467 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6468 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6469
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006470 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6471 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006472 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6473 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006474 1, &mPointerSimple.currentProperties, &pointerCoords,
6475 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006476 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006477 getListener()->notifyMotion(&args);
6478 }
6479
6480 // Save state.
6481 if (down || hovering) {
6482 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6483 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6484 } else {
6485 mPointerSimple.reset();
6486 }
6487}
6488
6489void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6490 mPointerSimple.currentCoords.clear();
6491 mPointerSimple.currentProperties.clear();
6492
6493 dispatchPointerSimple(when, policyFlags, false, false);
6494}
6495
6496void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006497 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006498 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006499 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006500 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6501 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006502 PointerCoords pointerCoords[MAX_POINTERS];
6503 PointerProperties pointerProperties[MAX_POINTERS];
6504 uint32_t pointerCount = 0;
6505 while (!idBits.isEmpty()) {
6506 uint32_t id = idBits.clearFirstMarkedBit();
6507 uint32_t index = idToIndex[id];
6508 pointerProperties[pointerCount].copyFrom(properties[index]);
6509 pointerCoords[pointerCount].copyFrom(coords[index]);
6510
6511 if (changedId >= 0 && id == uint32_t(changedId)) {
6512 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6513 }
6514
6515 pointerCount += 1;
6516 }
6517
6518 ALOG_ASSERT(pointerCount != 0);
6519
6520 if (changedId >= 0 && pointerCount == 1) {
6521 // Replace initial down and final up action.
6522 // We can compare the action without masking off the changed pointer index
6523 // because we know the index is 0.
6524 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6525 action = AMOTION_EVENT_ACTION_DOWN;
6526 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6527 action = AMOTION_EVENT_ACTION_UP;
6528 } else {
6529 // Can't happen.
6530 ALOG_ASSERT(false);
6531 }
6532 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006533 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006534 const int32_t deviceId = getDeviceId();
6535 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006536 std::for_each(frames.begin(), frames.end(),
6537 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006538 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006539 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006540 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6541 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006542 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543 getListener()->notifyMotion(&args);
6544}
6545
6546bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6547 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6548 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6549 BitSet32 idBits) const {
6550 bool changed = false;
6551 while (!idBits.isEmpty()) {
6552 uint32_t id = idBits.clearFirstMarkedBit();
6553 uint32_t inIndex = inIdToIndex[id];
6554 uint32_t outIndex = outIdToIndex[id];
6555
6556 const PointerProperties& curInProperties = inProperties[inIndex];
6557 const PointerCoords& curInCoords = inCoords[inIndex];
6558 PointerProperties& curOutProperties = outProperties[outIndex];
6559 PointerCoords& curOutCoords = outCoords[outIndex];
6560
6561 if (curInProperties != curOutProperties) {
6562 curOutProperties.copyFrom(curInProperties);
6563 changed = true;
6564 }
6565
6566 if (curInCoords != curOutCoords) {
6567 curOutCoords.copyFrom(curInCoords);
6568 changed = true;
6569 }
6570 }
6571 return changed;
6572}
6573
6574void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006575 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006576 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6577 }
6578}
6579
Jeff Brownc9aa6282015-02-11 19:03:28 -08006580void TouchInputMapper::cancelTouch(nsecs_t when) {
6581 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006582 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006583}
6584
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006586 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006587 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006589 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6590 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6591 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592}
6593
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006594const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006595
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006596 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597#if DEBUG_VIRTUAL_KEYS
6598 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6599 "left=%d, top=%d, right=%d, bottom=%d",
6600 x, y,
6601 virtualKey.keyCode, virtualKey.scanCode,
6602 virtualKey.hitLeft, virtualKey.hitTop,
6603 virtualKey.hitRight, virtualKey.hitBottom);
6604#endif
6605
6606 if (virtualKey.isHit(x, y)) {
6607 return & virtualKey;
6608 }
6609 }
6610
Yi Kong9b14ac62018-07-17 13:48:38 -07006611 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006612}
6613
Michael Wright842500e2015-03-13 17:32:02 -07006614void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6615 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6616 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617
Michael Wright842500e2015-03-13 17:32:02 -07006618 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006619
6620 if (currentPointerCount == 0) {
6621 // No pointers to assign.
6622 return;
6623 }
6624
6625 if (lastPointerCount == 0) {
6626 // All pointers are new.
6627 for (uint32_t i = 0; i < currentPointerCount; i++) {
6628 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006629 current->rawPointerData.pointers[i].id = id;
6630 current->rawPointerData.idToIndex[id] = i;
6631 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006632 }
6633 return;
6634 }
6635
6636 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006637 && current->rawPointerData.pointers[0].toolType
6638 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006639 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006640 uint32_t id = last->rawPointerData.pointers[0].id;
6641 current->rawPointerData.pointers[0].id = id;
6642 current->rawPointerData.idToIndex[id] = 0;
6643 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006644 return;
6645 }
6646
6647 // General case.
6648 // We build a heap of squared euclidean distances between current and last pointers
6649 // associated with the current and last pointer indices. Then, we find the best
6650 // match (by distance) for each current pointer.
6651 // The pointers must have the same tool type but it is possible for them to
6652 // transition from hovering to touching or vice-versa while retaining the same id.
6653 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6654
6655 uint32_t heapSize = 0;
6656 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6657 currentPointerIndex++) {
6658 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6659 lastPointerIndex++) {
6660 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006661 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006662 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006663 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006664 if (currentPointer.toolType == lastPointer.toolType) {
6665 int64_t deltaX = currentPointer.x - lastPointer.x;
6666 int64_t deltaY = currentPointer.y - lastPointer.y;
6667
6668 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6669
6670 // Insert new element into the heap (sift up).
6671 heap[heapSize].currentPointerIndex = currentPointerIndex;
6672 heap[heapSize].lastPointerIndex = lastPointerIndex;
6673 heap[heapSize].distance = distance;
6674 heapSize += 1;
6675 }
6676 }
6677 }
6678
6679 // Heapify
6680 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6681 startIndex -= 1;
6682 for (uint32_t parentIndex = startIndex; ;) {
6683 uint32_t childIndex = parentIndex * 2 + 1;
6684 if (childIndex >= heapSize) {
6685 break;
6686 }
6687
6688 if (childIndex + 1 < heapSize
6689 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6690 childIndex += 1;
6691 }
6692
6693 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6694 break;
6695 }
6696
6697 swap(heap[parentIndex], heap[childIndex]);
6698 parentIndex = childIndex;
6699 }
6700 }
6701
6702#if DEBUG_POINTER_ASSIGNMENT
6703 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6704 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006705 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006706 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6707 heap[i].distance);
6708 }
6709#endif
6710
6711 // Pull matches out by increasing order of distance.
6712 // To avoid reassigning pointers that have already been matched, the loop keeps track
6713 // of which last and current pointers have been matched using the matchedXXXBits variables.
6714 // It also tracks the used pointer id bits.
6715 BitSet32 matchedLastBits(0);
6716 BitSet32 matchedCurrentBits(0);
6717 BitSet32 usedIdBits(0);
6718 bool first = true;
6719 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6720 while (heapSize > 0) {
6721 if (first) {
6722 // The first time through the loop, we just consume the root element of
6723 // the heap (the one with smallest distance).
6724 first = false;
6725 } else {
6726 // Previous iterations consumed the root element of the heap.
6727 // Pop root element off of the heap (sift down).
6728 heap[0] = heap[heapSize];
6729 for (uint32_t parentIndex = 0; ;) {
6730 uint32_t childIndex = parentIndex * 2 + 1;
6731 if (childIndex >= heapSize) {
6732 break;
6733 }
6734
6735 if (childIndex + 1 < heapSize
6736 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6737 childIndex += 1;
6738 }
6739
6740 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6741 break;
6742 }
6743
6744 swap(heap[parentIndex], heap[childIndex]);
6745 parentIndex = childIndex;
6746 }
6747
6748#if DEBUG_POINTER_ASSIGNMENT
6749 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6750 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006751 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006752 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6753 heap[i].distance);
6754 }
6755#endif
6756 }
6757
6758 heapSize -= 1;
6759
6760 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6761 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6762
6763 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6764 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6765
6766 matchedCurrentBits.markBit(currentPointerIndex);
6767 matchedLastBits.markBit(lastPointerIndex);
6768
Michael Wright842500e2015-03-13 17:32:02 -07006769 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6770 current->rawPointerData.pointers[currentPointerIndex].id = id;
6771 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6772 current->rawPointerData.markIdBit(id,
6773 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006774 usedIdBits.markBit(id);
6775
6776#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006777 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6778 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006779 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6780#endif
6781 break;
6782 }
6783 }
6784
6785 // Assign fresh ids to pointers that were not matched in the process.
6786 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6787 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6788 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6789
Michael Wright842500e2015-03-13 17:32:02 -07006790 current->rawPointerData.pointers[currentPointerIndex].id = id;
6791 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6792 current->rawPointerData.markIdBit(id,
6793 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006794
6795#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006796 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006797#endif
6798 }
6799}
6800
6801int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6802 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6803 return AKEY_STATE_VIRTUAL;
6804 }
6805
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006806 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006807 if (virtualKey.keyCode == keyCode) {
6808 return AKEY_STATE_UP;
6809 }
6810 }
6811
6812 return AKEY_STATE_UNKNOWN;
6813}
6814
6815int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6816 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6817 return AKEY_STATE_VIRTUAL;
6818 }
6819
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006820 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006821 if (virtualKey.scanCode == scanCode) {
6822 return AKEY_STATE_UP;
6823 }
6824 }
6825
6826 return AKEY_STATE_UNKNOWN;
6827}
6828
6829bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6830 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006831 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006832 for (size_t i = 0; i < numCodes; i++) {
6833 if (virtualKey.keyCode == keyCodes[i]) {
6834 outFlags[i] = 1;
6835 }
6836 }
6837 }
6838
6839 return true;
6840}
6841
Arthur Hungc23540e2018-11-29 20:42:11 +08006842std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6843 if (mParameters.hasAssociatedDisplay) {
6844 if (mDeviceMode == DEVICE_MODE_POINTER) {
6845 return std::make_optional(mPointerController->getDisplayId());
6846 } else {
6847 return std::make_optional(mViewport.displayId);
6848 }
6849 }
6850 return std::nullopt;
6851}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006852
6853// --- SingleTouchInputMapper ---
6854
6855SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6856 TouchInputMapper(device) {
6857}
6858
6859SingleTouchInputMapper::~SingleTouchInputMapper() {
6860}
6861
6862void SingleTouchInputMapper::reset(nsecs_t when) {
6863 mSingleTouchMotionAccumulator.reset(getDevice());
6864
6865 TouchInputMapper::reset(when);
6866}
6867
6868void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6869 TouchInputMapper::process(rawEvent);
6870
6871 mSingleTouchMotionAccumulator.process(rawEvent);
6872}
6873
Michael Wright842500e2015-03-13 17:32:02 -07006874void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006875 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006876 outState->rawPointerData.pointerCount = 1;
6877 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006878
6879 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6880 && (mTouchButtonAccumulator.isHovering()
6881 || (mRawPointerAxes.pressure.valid
6882 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006883 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006884
Michael Wright842500e2015-03-13 17:32:02 -07006885 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006886 outPointer.id = 0;
6887 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6888 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6889 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6890 outPointer.touchMajor = 0;
6891 outPointer.touchMinor = 0;
6892 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6893 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6894 outPointer.orientation = 0;
6895 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6896 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6897 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6898 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6899 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6900 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6901 }
6902 outPointer.isHovering = isHovering;
6903 }
6904}
6905
6906void SingleTouchInputMapper::configureRawPointerAxes() {
6907 TouchInputMapper::configureRawPointerAxes();
6908
6909 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6910 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6911 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6912 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6913 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6914 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6915 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6916}
6917
6918bool SingleTouchInputMapper::hasStylus() const {
6919 return mTouchButtonAccumulator.hasStylus();
6920}
6921
6922
6923// --- MultiTouchInputMapper ---
6924
6925MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6926 TouchInputMapper(device) {
6927}
6928
6929MultiTouchInputMapper::~MultiTouchInputMapper() {
6930}
6931
6932void MultiTouchInputMapper::reset(nsecs_t when) {
6933 mMultiTouchMotionAccumulator.reset(getDevice());
6934
6935 mPointerIdBits.clear();
6936
6937 TouchInputMapper::reset(when);
6938}
6939
6940void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6941 TouchInputMapper::process(rawEvent);
6942
6943 mMultiTouchMotionAccumulator.process(rawEvent);
6944}
6945
Michael Wright842500e2015-03-13 17:32:02 -07006946void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6948 size_t outCount = 0;
6949 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006950 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006951
6952 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6953 const MultiTouchMotionAccumulator::Slot* inSlot =
6954 mMultiTouchMotionAccumulator.getSlot(inIndex);
6955 if (!inSlot->isInUse()) {
6956 continue;
6957 }
6958
6959 if (outCount >= MAX_POINTERS) {
6960#if DEBUG_POINTERS
6961 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6962 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006963 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006964#endif
6965 break; // too many fingers!
6966 }
6967
Michael Wright842500e2015-03-13 17:32:02 -07006968 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006969 outPointer.x = inSlot->getX();
6970 outPointer.y = inSlot->getY();
6971 outPointer.pressure = inSlot->getPressure();
6972 outPointer.touchMajor = inSlot->getTouchMajor();
6973 outPointer.touchMinor = inSlot->getTouchMinor();
6974 outPointer.toolMajor = inSlot->getToolMajor();
6975 outPointer.toolMinor = inSlot->getToolMinor();
6976 outPointer.orientation = inSlot->getOrientation();
6977 outPointer.distance = inSlot->getDistance();
6978 outPointer.tiltX = 0;
6979 outPointer.tiltY = 0;
6980
6981 outPointer.toolType = inSlot->getToolType();
6982 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6983 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6984 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6985 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6986 }
6987 }
6988
6989 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6990 && (mTouchButtonAccumulator.isHovering()
6991 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6992 outPointer.isHovering = isHovering;
6993
6994 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006995 if (mHavePointerIds) {
6996 int32_t trackingId = inSlot->getTrackingId();
6997 int32_t id = -1;
6998 if (trackingId >= 0) {
6999 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7000 uint32_t n = idBits.clearFirstMarkedBit();
7001 if (mPointerTrackingIdMap[n] == trackingId) {
7002 id = n;
7003 }
7004 }
7005
7006 if (id < 0 && !mPointerIdBits.isFull()) {
7007 id = mPointerIdBits.markFirstUnmarkedBit();
7008 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007009 }
Michael Wright842500e2015-03-13 17:32:02 -07007010 }
gaoshang1a632de2016-08-24 10:23:50 +08007011 if (id < 0) {
7012 mHavePointerIds = false;
7013 outState->rawPointerData.clearIdBits();
7014 newPointerIdBits.clear();
7015 } else {
7016 outPointer.id = id;
7017 outState->rawPointerData.idToIndex[id] = outCount;
7018 outState->rawPointerData.markIdBit(id, isHovering);
7019 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007020 }
Michael Wright842500e2015-03-13 17:32:02 -07007021 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007022 outCount += 1;
7023 }
7024
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007025 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007026 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007027 mPointerIdBits = newPointerIdBits;
7028
7029 mMultiTouchMotionAccumulator.finishSync();
7030}
7031
7032void MultiTouchInputMapper::configureRawPointerAxes() {
7033 TouchInputMapper::configureRawPointerAxes();
7034
7035 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7036 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7037 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7038 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7039 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7040 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7041 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7042 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7043 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7044 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7045 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7046
7047 if (mRawPointerAxes.trackingId.valid
7048 && mRawPointerAxes.slot.valid
7049 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7050 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7051 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007052 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7053 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007054 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007055 slotCount = MAX_SLOTS;
7056 }
7057 mMultiTouchMotionAccumulator.configure(getDevice(),
7058 slotCount, true /*usingSlotsProtocol*/);
7059 } else {
7060 mMultiTouchMotionAccumulator.configure(getDevice(),
7061 MAX_POINTERS, false /*usingSlotsProtocol*/);
7062 }
7063}
7064
7065bool MultiTouchInputMapper::hasStylus() const {
7066 return mMultiTouchMotionAccumulator.hasStylus()
7067 || mTouchButtonAccumulator.hasStylus();
7068}
7069
Michael Wright842500e2015-03-13 17:32:02 -07007070// --- ExternalStylusInputMapper
7071
7072ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7073 InputMapper(device) {
7074
7075}
7076
7077uint32_t ExternalStylusInputMapper::getSources() {
7078 return AINPUT_SOURCE_STYLUS;
7079}
7080
7081void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7082 InputMapper::populateDeviceInfo(info);
7083 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7084 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7085}
7086
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007087void ExternalStylusInputMapper::dump(std::string& dump) {
7088 dump += INDENT2 "External Stylus Input Mapper:\n";
7089 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007090 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007091 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007092 dumpStylusState(dump, mStylusState);
7093}
7094
7095void ExternalStylusInputMapper::configure(nsecs_t when,
7096 const InputReaderConfiguration* config, uint32_t changes) {
7097 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7098 mTouchButtonAccumulator.configure(getDevice());
7099}
7100
7101void ExternalStylusInputMapper::reset(nsecs_t when) {
7102 InputDevice* device = getDevice();
7103 mSingleTouchMotionAccumulator.reset(device);
7104 mTouchButtonAccumulator.reset(device);
7105 InputMapper::reset(when);
7106}
7107
7108void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7109 mSingleTouchMotionAccumulator.process(rawEvent);
7110 mTouchButtonAccumulator.process(rawEvent);
7111
7112 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7113 sync(rawEvent->when);
7114 }
7115}
7116
7117void ExternalStylusInputMapper::sync(nsecs_t when) {
7118 mStylusState.clear();
7119
7120 mStylusState.when = when;
7121
Michael Wright45ccacf2015-04-21 19:01:58 +01007122 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7123 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7124 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7125 }
7126
Michael Wright842500e2015-03-13 17:32:02 -07007127 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7128 if (mRawPressureAxis.valid) {
7129 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7130 } else if (mTouchButtonAccumulator.isToolActive()) {
7131 mStylusState.pressure = 1.0f;
7132 } else {
7133 mStylusState.pressure = 0.0f;
7134 }
7135
7136 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007137
7138 mContext->dispatchExternalStylusState(mStylusState);
7139}
7140
Michael Wrightd02c5b62014-02-10 15:10:22 -08007141
7142// --- JoystickInputMapper ---
7143
7144JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7145 InputMapper(device) {
7146}
7147
7148JoystickInputMapper::~JoystickInputMapper() {
7149}
7150
7151uint32_t JoystickInputMapper::getSources() {
7152 return AINPUT_SOURCE_JOYSTICK;
7153}
7154
7155void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7156 InputMapper::populateDeviceInfo(info);
7157
7158 for (size_t i = 0; i < mAxes.size(); i++) {
7159 const Axis& axis = mAxes.valueAt(i);
7160 addMotionRange(axis.axisInfo.axis, axis, info);
7161
7162 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7163 addMotionRange(axis.axisInfo.highAxis, axis, info);
7164
7165 }
7166 }
7167}
7168
7169void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7170 InputDeviceInfo* info) {
7171 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7172 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7173 /* In order to ease the transition for developers from using the old axes
7174 * to the newer, more semantically correct axes, we'll continue to register
7175 * the old axes as duplicates of their corresponding new ones. */
7176 int32_t compatAxis = getCompatAxis(axisId);
7177 if (compatAxis >= 0) {
7178 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7179 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7180 }
7181}
7182
7183/* A mapping from axes the joystick actually has to the axes that should be
7184 * artificially created for compatibility purposes.
7185 * Returns -1 if no compatibility axis is needed. */
7186int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7187 switch(axis) {
7188 case AMOTION_EVENT_AXIS_LTRIGGER:
7189 return AMOTION_EVENT_AXIS_BRAKE;
7190 case AMOTION_EVENT_AXIS_RTRIGGER:
7191 return AMOTION_EVENT_AXIS_GAS;
7192 }
7193 return -1;
7194}
7195
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007196void JoystickInputMapper::dump(std::string& dump) {
7197 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007198
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007199 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007200 size_t numAxes = mAxes.size();
7201 for (size_t i = 0; i < numAxes; i++) {
7202 const Axis& axis = mAxes.valueAt(i);
7203 const char* label = getAxisLabel(axis.axisInfo.axis);
7204 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007205 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007206 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007207 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007208 }
7209 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7210 label = getAxisLabel(axis.axisInfo.highAxis);
7211 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007212 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007213 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007214 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007215 axis.axisInfo.splitValue);
7216 }
7217 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007218 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007219 }
7220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007221 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 -08007222 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007223 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007224 "highScale=%0.5f, highOffset=%0.5f\n",
7225 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007226 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007227 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7228 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7229 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7230 }
7231}
7232
7233void JoystickInputMapper::configure(nsecs_t when,
7234 const InputReaderConfiguration* config, uint32_t changes) {
7235 InputMapper::configure(when, config, changes);
7236
7237 if (!changes) { // first time only
7238 // Collect all axes.
7239 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7240 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7241 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7242 continue; // axis must be claimed by a different device
7243 }
7244
7245 RawAbsoluteAxisInfo rawAxisInfo;
7246 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7247 if (rawAxisInfo.valid) {
7248 // Map axis.
7249 AxisInfo axisInfo;
7250 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7251 if (!explicitlyMapped) {
7252 // Axis is not explicitly mapped, will choose a generic axis later.
7253 axisInfo.mode = AxisInfo::MODE_NORMAL;
7254 axisInfo.axis = -1;
7255 }
7256
7257 // Apply flat override.
7258 int32_t rawFlat = axisInfo.flatOverride < 0
7259 ? rawAxisInfo.flat : axisInfo.flatOverride;
7260
7261 // Calculate scaling factors and limits.
7262 Axis axis;
7263 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7264 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7265 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7266 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7267 scale, 0.0f, highScale, 0.0f,
7268 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7269 rawAxisInfo.resolution * scale);
7270 } else if (isCenteredAxis(axisInfo.axis)) {
7271 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7272 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7273 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7274 scale, offset, scale, offset,
7275 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7276 rawAxisInfo.resolution * scale);
7277 } else {
7278 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7279 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7280 scale, 0.0f, scale, 0.0f,
7281 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7282 rawAxisInfo.resolution * scale);
7283 }
7284
7285 // To eliminate noise while the joystick is at rest, filter out small variations
7286 // in axis values up front.
7287 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7288
7289 mAxes.add(abs, axis);
7290 }
7291 }
7292
7293 // If there are too many axes, start dropping them.
7294 // Prefer to keep explicitly mapped axes.
7295 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007296 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007297 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007298 pruneAxes(true);
7299 pruneAxes(false);
7300 }
7301
7302 // Assign generic axis ids to remaining axes.
7303 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7304 size_t numAxes = mAxes.size();
7305 for (size_t i = 0; i < numAxes; i++) {
7306 Axis& axis = mAxes.editValueAt(i);
7307 if (axis.axisInfo.axis < 0) {
7308 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7309 && haveAxis(nextGenericAxisId)) {
7310 nextGenericAxisId += 1;
7311 }
7312
7313 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7314 axis.axisInfo.axis = nextGenericAxisId;
7315 nextGenericAxisId += 1;
7316 } else {
7317 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7318 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007319 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007320 mAxes.removeItemsAt(i--);
7321 numAxes -= 1;
7322 }
7323 }
7324 }
7325 }
7326}
7327
7328bool JoystickInputMapper::haveAxis(int32_t axisId) {
7329 size_t numAxes = mAxes.size();
7330 for (size_t i = 0; i < numAxes; i++) {
7331 const Axis& axis = mAxes.valueAt(i);
7332 if (axis.axisInfo.axis == axisId
7333 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7334 && axis.axisInfo.highAxis == axisId)) {
7335 return true;
7336 }
7337 }
7338 return false;
7339}
7340
7341void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7342 size_t i = mAxes.size();
7343 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7344 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7345 continue;
7346 }
7347 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007348 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007349 mAxes.removeItemsAt(i);
7350 }
7351}
7352
7353bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7354 switch (axis) {
7355 case AMOTION_EVENT_AXIS_X:
7356 case AMOTION_EVENT_AXIS_Y:
7357 case AMOTION_EVENT_AXIS_Z:
7358 case AMOTION_EVENT_AXIS_RX:
7359 case AMOTION_EVENT_AXIS_RY:
7360 case AMOTION_EVENT_AXIS_RZ:
7361 case AMOTION_EVENT_AXIS_HAT_X:
7362 case AMOTION_EVENT_AXIS_HAT_Y:
7363 case AMOTION_EVENT_AXIS_ORIENTATION:
7364 case AMOTION_EVENT_AXIS_RUDDER:
7365 case AMOTION_EVENT_AXIS_WHEEL:
7366 return true;
7367 default:
7368 return false;
7369 }
7370}
7371
7372void JoystickInputMapper::reset(nsecs_t when) {
7373 // Recenter all axes.
7374 size_t numAxes = mAxes.size();
7375 for (size_t i = 0; i < numAxes; i++) {
7376 Axis& axis = mAxes.editValueAt(i);
7377 axis.resetValue();
7378 }
7379
7380 InputMapper::reset(when);
7381}
7382
7383void JoystickInputMapper::process(const RawEvent* rawEvent) {
7384 switch (rawEvent->type) {
7385 case EV_ABS: {
7386 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7387 if (index >= 0) {
7388 Axis& axis = mAxes.editValueAt(index);
7389 float newValue, highNewValue;
7390 switch (axis.axisInfo.mode) {
7391 case AxisInfo::MODE_INVERT:
7392 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7393 * axis.scale + axis.offset;
7394 highNewValue = 0.0f;
7395 break;
7396 case AxisInfo::MODE_SPLIT:
7397 if (rawEvent->value < axis.axisInfo.splitValue) {
7398 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7399 * axis.scale + axis.offset;
7400 highNewValue = 0.0f;
7401 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7402 newValue = 0.0f;
7403 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7404 * axis.highScale + axis.highOffset;
7405 } else {
7406 newValue = 0.0f;
7407 highNewValue = 0.0f;
7408 }
7409 break;
7410 default:
7411 newValue = rawEvent->value * axis.scale + axis.offset;
7412 highNewValue = 0.0f;
7413 break;
7414 }
7415 axis.newValue = newValue;
7416 axis.highNewValue = highNewValue;
7417 }
7418 break;
7419 }
7420
7421 case EV_SYN:
7422 switch (rawEvent->code) {
7423 case SYN_REPORT:
7424 sync(rawEvent->when, false /*force*/);
7425 break;
7426 }
7427 break;
7428 }
7429}
7430
7431void JoystickInputMapper::sync(nsecs_t when, bool force) {
7432 if (!filterAxes(force)) {
7433 return;
7434 }
7435
7436 int32_t metaState = mContext->getGlobalMetaState();
7437 int32_t buttonState = 0;
7438
7439 PointerProperties pointerProperties;
7440 pointerProperties.clear();
7441 pointerProperties.id = 0;
7442 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7443
7444 PointerCoords pointerCoords;
7445 pointerCoords.clear();
7446
7447 size_t numAxes = mAxes.size();
7448 for (size_t i = 0; i < numAxes; i++) {
7449 const Axis& axis = mAxes.valueAt(i);
7450 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7451 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7452 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7453 axis.highCurrentValue);
7454 }
7455 }
7456
7457 // Moving a joystick axis should not wake the device because joysticks can
7458 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7459 // button will likely wake the device.
7460 // TODO: Use the input device configuration to control this behavior more finely.
7461 uint32_t policyFlags = 0;
7462
Prabir Pradhan42611e02018-11-27 14:04:02 -08007463 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7464 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007465 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7466 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7467 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007468 getListener()->notifyMotion(&args);
7469}
7470
7471void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7472 int32_t axis, float value) {
7473 pointerCoords->setAxisValue(axis, value);
7474 /* In order to ease the transition for developers from using the old axes
7475 * to the newer, more semantically correct axes, we'll continue to produce
7476 * values for the old axes as mirrors of the value of their corresponding
7477 * new axes. */
7478 int32_t compatAxis = getCompatAxis(axis);
7479 if (compatAxis >= 0) {
7480 pointerCoords->setAxisValue(compatAxis, value);
7481 }
7482}
7483
7484bool JoystickInputMapper::filterAxes(bool force) {
7485 bool atLeastOneSignificantChange = force;
7486 size_t numAxes = mAxes.size();
7487 for (size_t i = 0; i < numAxes; i++) {
7488 Axis& axis = mAxes.editValueAt(i);
7489 if (force || hasValueChangedSignificantly(axis.filter,
7490 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7491 axis.currentValue = axis.newValue;
7492 atLeastOneSignificantChange = true;
7493 }
7494 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7495 if (force || hasValueChangedSignificantly(axis.filter,
7496 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7497 axis.highCurrentValue = axis.highNewValue;
7498 atLeastOneSignificantChange = true;
7499 }
7500 }
7501 }
7502 return atLeastOneSignificantChange;
7503}
7504
7505bool JoystickInputMapper::hasValueChangedSignificantly(
7506 float filter, float newValue, float currentValue, float min, float max) {
7507 if (newValue != currentValue) {
7508 // Filter out small changes in value unless the value is converging on the axis
7509 // bounds or center point. This is intended to reduce the amount of information
7510 // sent to applications by particularly noisy joysticks (such as PS3).
7511 if (fabs(newValue - currentValue) > filter
7512 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7513 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7514 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7515 return true;
7516 }
7517 }
7518 return false;
7519}
7520
7521bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7522 float filter, float newValue, float currentValue, float thresholdValue) {
7523 float newDistance = fabs(newValue - thresholdValue);
7524 if (newDistance < filter) {
7525 float oldDistance = fabs(currentValue - thresholdValue);
7526 if (newDistance < oldDistance) {
7527 return true;
7528 }
7529 }
7530 return false;
7531}
7532
7533} // namespace android