blob: ae46ddb9c36febef0dc36020b772375fa0174215 [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,
Siarhei Vishniakou05247bb2019-03-22 17:11:21 -07004317 mStatistics.min, mStatistics.max,
4318 mStatistics.mean(), mStatistics.stdev(), mStatistics.count);
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004319 mStatistics.reset(now);
4320 }
4321}
4322
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323void TouchInputMapper::process(const RawEvent* rawEvent) {
4324 mCursorButtonAccumulator.process(rawEvent);
4325 mCursorScrollAccumulator.process(rawEvent);
4326 mTouchButtonAccumulator.process(rawEvent);
4327
4328 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004329 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004330 sync(rawEvent->when);
4331 }
4332}
4333
4334void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004335 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004336 mRawStatesPending.emplace_back();
4337
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00004338 RawState& next = mRawStatesPending.back();
4339 next.clear();
4340 next.when = when;
Michael Wright842500e2015-03-13 17:32:02 -07004341
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 // Sync button state.
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00004343 next.buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004344 | mCursorButtonAccumulator.getButtonState();
4345
Michael Wright842500e2015-03-13 17:32:02 -07004346 // Sync scroll
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00004347 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4348 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349 mCursorScrollAccumulator.finishSync();
4350
Michael Wright842500e2015-03-13 17:32:02 -07004351 // Sync touch
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00004352 syncTouch(when, &next);
Michael Wright842500e2015-03-13 17:32:02 -07004353
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00004354 // The last RawState is actually the second to last, since we just added a new state
4355 const RawState& last =
4356 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Michael Wright842500e2015-03-13 17:32:02 -07004357 // Assign pointer ids.
4358 if (!mHavePointerIds) {
4359 assignPointerIds(last, next);
4360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004361
4362#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004363 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4364 "hovering ids 0x%08x -> 0x%08x",
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00004365 last.rawPointerData.pointerCount,
4366 next.rawPointerData.pointerCount,
4367 last.rawPointerData.touchingIdBits.value,
4368 next.rawPointerData.touchingIdBits.value,
4369 last.rawPointerData.hoveringIdBits.value,
4370 next.rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004371#endif
4372
Michael Wright842500e2015-03-13 17:32:02 -07004373 processRawTouches(false /*timeout*/);
4374}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004375
Michael Wright842500e2015-03-13 17:32:02 -07004376void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4378 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004379 mCurrentRawState.clear();
4380 mRawStatesPending.clear();
4381 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 }
4383
Michael Wright842500e2015-03-13 17:32:02 -07004384 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4385 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4386 // touching the current state will only observe the events that have been dispatched to the
4387 // rest of the pipeline.
4388 const size_t N = mRawStatesPending.size();
4389 size_t count;
4390 for(count = 0; count < N; count++) {
4391 const RawState& next = mRawStatesPending[count];
4392
4393 // A failure to assign the stylus id means that we're waiting on stylus data
4394 // and so should defer the rest of the pipeline.
4395 if (assignExternalStylusId(next, timeout)) {
4396 break;
4397 }
4398
4399 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004400 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004401 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004402 if (mCurrentRawState.when < mLastRawState.when) {
4403 mCurrentRawState.when = mLastRawState.when;
4404 }
Michael Wright842500e2015-03-13 17:32:02 -07004405 cookAndDispatch(mCurrentRawState.when);
4406 }
4407 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004408 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004409 }
4410
Michael Wright842500e2015-03-13 17:32:02 -07004411 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004412 if (timeout) {
4413 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4414 clearStylusDataPendingFlags();
4415 mCurrentRawState.copyFrom(mLastRawState);
4416#if DEBUG_STYLUS_FUSION
4417 ALOGD("Timeout expired, synthesizing event with new stylus data");
4418#endif
4419 cookAndDispatch(when);
4420 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4421 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4422 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4423 }
Michael Wright842500e2015-03-13 17:32:02 -07004424 }
4425}
4426
4427void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4428 // Always start with a clean state.
4429 mCurrentCookedState.clear();
4430
4431 // Apply stylus buttons to current raw state.
4432 applyExternalStylusButtonState(when);
4433
4434 // Handle policy on initial down or hover events.
4435 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4436 && mCurrentRawState.rawPointerData.pointerCount != 0;
4437
4438 uint32_t policyFlags = 0;
4439 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4440 if (initialDown || buttonsPressed) {
4441 // If this is a touch screen, hide the pointer on an initial down.
4442 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4443 getContext()->fadePointer();
4444 }
4445
4446 if (mParameters.wake) {
4447 policyFlags |= POLICY_FLAG_WAKE;
4448 }
4449 }
4450
4451 // Consume raw off-screen touches before cooking pointer data.
4452 // If touches are consumed, subsequent code will not receive any pointer data.
4453 if (consumeRawTouches(when, policyFlags)) {
4454 mCurrentRawState.rawPointerData.clear();
4455 }
4456
4457 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4458 // with cooked pointer data that has the same ids and indices as the raw data.
4459 // The following code can use either the raw or cooked data, as needed.
4460 cookPointerData();
4461
4462 // Apply stylus pressure to current cooked state.
4463 applyExternalStylusTouchState(when);
4464
4465 // Synthesize key down from raw buttons if needed.
4466 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004467 mViewport.displayId, policyFlags,
4468 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004469
4470 // Dispatch the touches either directly or by translation through a pointer on screen.
4471 if (mDeviceMode == DEVICE_MODE_POINTER) {
4472 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4473 !idBits.isEmpty(); ) {
4474 uint32_t id = idBits.clearFirstMarkedBit();
4475 const RawPointerData::Pointer& pointer =
4476 mCurrentRawState.rawPointerData.pointerForId(id);
4477 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4478 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4479 mCurrentCookedState.stylusIdBits.markBit(id);
4480 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4481 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4482 mCurrentCookedState.fingerIdBits.markBit(id);
4483 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4484 mCurrentCookedState.mouseIdBits.markBit(id);
4485 }
4486 }
4487 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4488 !idBits.isEmpty(); ) {
4489 uint32_t id = idBits.clearFirstMarkedBit();
4490 const RawPointerData::Pointer& pointer =
4491 mCurrentRawState.rawPointerData.pointerForId(id);
4492 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4493 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4494 mCurrentCookedState.stylusIdBits.markBit(id);
4495 }
4496 }
4497
4498 // Stylus takes precedence over all tools, then mouse, then finger.
4499 PointerUsage pointerUsage = mPointerUsage;
4500 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4501 mCurrentCookedState.mouseIdBits.clear();
4502 mCurrentCookedState.fingerIdBits.clear();
4503 pointerUsage = POINTER_USAGE_STYLUS;
4504 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4505 mCurrentCookedState.fingerIdBits.clear();
4506 pointerUsage = POINTER_USAGE_MOUSE;
4507 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4508 isPointerDown(mCurrentRawState.buttonState)) {
4509 pointerUsage = POINTER_USAGE_GESTURES;
4510 }
4511
4512 dispatchPointerUsage(when, policyFlags, pointerUsage);
4513 } else {
4514 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004515 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004516 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4517 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4518
4519 mPointerController->setButtonState(mCurrentRawState.buttonState);
4520 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4521 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004522 mCurrentCookedState.cookedPointerData.touchingIdBits,
4523 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004524 }
4525
Michael Wright8e812822015-06-22 16:18:21 +01004526 if (!mCurrentMotionAborted) {
4527 dispatchButtonRelease(when, policyFlags);
4528 dispatchHoverExit(when, policyFlags);
4529 dispatchTouches(when, policyFlags);
4530 dispatchHoverEnterAndMove(when, policyFlags);
4531 dispatchButtonPress(when, policyFlags);
4532 }
4533
4534 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4535 mCurrentMotionAborted = false;
4536 }
Michael Wright842500e2015-03-13 17:32:02 -07004537 }
4538
4539 // Synthesize key up from raw buttons if needed.
4540 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004541 mViewport.displayId, policyFlags,
4542 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004543
4544 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004545 mCurrentRawState.rawVScroll = 0;
4546 mCurrentRawState.rawHScroll = 0;
4547
4548 // Copy current touch to last touch in preparation for the next cycle.
4549 mLastRawState.copyFrom(mCurrentRawState);
4550 mLastCookedState.copyFrom(mCurrentCookedState);
4551}
4552
4553void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004554 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004555 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4556 }
4557}
4558
4559void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004560 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4561 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004562
Michael Wright53dca3a2015-04-23 17:39:53 +01004563 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4564 float pressure = mExternalStylusState.pressure;
4565 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4566 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4567 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4568 }
4569 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4570 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4571
4572 PointerProperties& properties =
4573 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004574 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4575 properties.toolType = mExternalStylusState.toolType;
4576 }
4577 }
4578}
4579
4580bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4581 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4582 return false;
4583 }
4584
4585 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4586 && state.rawPointerData.pointerCount != 0;
4587 if (initialDown) {
4588 if (mExternalStylusState.pressure != 0.0f) {
4589#if DEBUG_STYLUS_FUSION
4590 ALOGD("Have both stylus and touch data, beginning fusion");
4591#endif
4592 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4593 } else if (timeout) {
4594#if DEBUG_STYLUS_FUSION
4595 ALOGD("Timeout expired, assuming touch is not a stylus.");
4596#endif
4597 resetExternalStylus();
4598 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004599 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4600 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004601 }
4602#if DEBUG_STYLUS_FUSION
4603 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004604 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004605#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004606 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004607 return true;
4608 }
4609 }
4610
4611 // Check if the stylus pointer has gone up.
4612 if (mExternalStylusId != -1 &&
4613 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4614#if DEBUG_STYLUS_FUSION
4615 ALOGD("Stylus pointer is going up");
4616#endif
4617 mExternalStylusId = -1;
4618 }
4619
4620 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621}
4622
4623void TouchInputMapper::timeoutExpired(nsecs_t when) {
4624 if (mDeviceMode == DEVICE_MODE_POINTER) {
4625 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4626 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4627 }
Michael Wright842500e2015-03-13 17:32:02 -07004628 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004629 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004630 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004631 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4632 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004633 }
4634 }
4635}
4636
4637void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004638 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004639 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004640 // We're either in the middle of a fused stream of data or we're waiting on data before
4641 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4642 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004643 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004644 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 }
4646}
4647
4648bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4649 // Check for release of a virtual key.
4650 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004651 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 // Pointer went up while virtual key was down.
4653 mCurrentVirtualKey.down = false;
4654 if (!mCurrentVirtualKey.ignored) {
4655#if DEBUG_VIRTUAL_KEYS
4656 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4657 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4658#endif
4659 dispatchVirtualKey(when, policyFlags,
4660 AKEY_EVENT_ACTION_UP,
4661 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4662 }
4663 return true;
4664 }
4665
Michael Wright842500e2015-03-13 17:32:02 -07004666 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4667 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4668 const RawPointerData::Pointer& pointer =
4669 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4671 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4672 // Pointer is still within the space of the virtual key.
4673 return true;
4674 }
4675 }
4676
4677 // Pointer left virtual key area or another pointer also went down.
4678 // Send key cancellation but do not consume the touch yet.
4679 // This is useful when the user swipes through from the virtual key area
4680 // into the main display surface.
4681 mCurrentVirtualKey.down = false;
4682 if (!mCurrentVirtualKey.ignored) {
4683#if DEBUG_VIRTUAL_KEYS
4684 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4685 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4686#endif
4687 dispatchVirtualKey(when, policyFlags,
4688 AKEY_EVENT_ACTION_UP,
4689 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4690 | AKEY_EVENT_FLAG_CANCELED);
4691 }
4692 }
4693
Michael Wright842500e2015-03-13 17:32:02 -07004694 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4695 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004696 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004697 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4698 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4700 // If exactly one pointer went down, check for virtual key hit.
4701 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004702 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004703 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4704 if (virtualKey) {
4705 mCurrentVirtualKey.down = true;
4706 mCurrentVirtualKey.downTime = when;
4707 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4708 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4709 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4710 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4711
4712 if (!mCurrentVirtualKey.ignored) {
4713#if DEBUG_VIRTUAL_KEYS
4714 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4715 mCurrentVirtualKey.keyCode,
4716 mCurrentVirtualKey.scanCode);
4717#endif
4718 dispatchVirtualKey(when, policyFlags,
4719 AKEY_EVENT_ACTION_DOWN,
4720 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4721 }
4722 }
4723 }
4724 return true;
4725 }
4726 }
4727
4728 // Disable all virtual key touches that happen within a short time interval of the
4729 // most recent touch within the screen area. The idea is to filter out stray
4730 // virtual key presses when interacting with the touch screen.
4731 //
4732 // Problems we're trying to solve:
4733 //
4734 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4735 // virtual key area that is implemented by a separate touch panel and accidentally
4736 // triggers a virtual key.
4737 //
4738 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4739 // area and accidentally triggers a virtual key. This often happens when virtual keys
4740 // are layed out below the screen near to where the on screen keyboard's space bar
4741 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004742 if (mConfig.virtualKeyQuietTime > 0 &&
4743 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4745 }
4746 return false;
4747}
4748
4749void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4750 int32_t keyEventAction, int32_t keyEventFlags) {
4751 int32_t keyCode = mCurrentVirtualKey.keyCode;
4752 int32_t scanCode = mCurrentVirtualKey.scanCode;
4753 nsecs_t downTime = mCurrentVirtualKey.downTime;
4754 int32_t metaState = mContext->getGlobalMetaState();
4755 policyFlags |= POLICY_FLAG_VIRTUAL;
4756
Prabir Pradhan42611e02018-11-27 14:04:02 -08004757 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4758 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004759 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 getListener()->notifyKey(&args);
4761}
4762
Michael Wright8e812822015-06-22 16:18:21 +01004763void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4764 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4765 if (!currentIdBits.isEmpty()) {
4766 int32_t metaState = getContext()->getGlobalMetaState();
4767 int32_t buttonState = mCurrentCookedState.buttonState;
4768 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4769 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004770 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004771 mCurrentCookedState.cookedPointerData.pointerProperties,
4772 mCurrentCookedState.cookedPointerData.pointerCoords,
4773 mCurrentCookedState.cookedPointerData.idToIndex,
4774 currentIdBits, -1,
4775 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4776 mCurrentMotionAborted = true;
4777 }
4778}
4779
Michael Wrightd02c5b62014-02-10 15:10:22 -08004780void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004781 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4782 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004784 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785
4786 if (currentIdBits == lastIdBits) {
4787 if (!currentIdBits.isEmpty()) {
4788 // No pointer id changes so this is a move event.
4789 // The listener takes care of batching moves so we don't have to deal with that here.
4790 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004791 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004792 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004793 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004794 mCurrentCookedState.cookedPointerData.pointerProperties,
4795 mCurrentCookedState.cookedPointerData.pointerCoords,
4796 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 currentIdBits, -1,
4798 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4799 }
4800 } else {
4801 // There may be pointers going up and pointers going down and pointers moving
4802 // all at the same time.
4803 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4804 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4805 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4806 BitSet32 dispatchedIdBits(lastIdBits.value);
4807
4808 // Update last coordinates of pointers that have moved so that we observe the new
4809 // pointer positions at the same time as other pointers that have just gone up.
4810 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004811 mCurrentCookedState.cookedPointerData.pointerProperties,
4812 mCurrentCookedState.cookedPointerData.pointerCoords,
4813 mCurrentCookedState.cookedPointerData.idToIndex,
4814 mLastCookedState.cookedPointerData.pointerProperties,
4815 mLastCookedState.cookedPointerData.pointerCoords,
4816 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004817 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004818 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004819 moveNeeded = true;
4820 }
4821
4822 // Dispatch pointer up events.
4823 while (!upIdBits.isEmpty()) {
4824 uint32_t upId = upIdBits.clearFirstMarkedBit();
4825
4826 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004827 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004828 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004829 mLastCookedState.cookedPointerData.pointerProperties,
4830 mLastCookedState.cookedPointerData.pointerCoords,
4831 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004832 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004833 dispatchedIdBits.clearBit(upId);
4834 }
4835
4836 // Dispatch move events if any of the remaining pointers moved from their old locations.
4837 // Although applications receive new locations as part of individual pointer up
4838 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004839 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004840 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4841 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004842 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004843 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004844 mCurrentCookedState.cookedPointerData.pointerProperties,
4845 mCurrentCookedState.cookedPointerData.pointerCoords,
4846 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004847 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 }
4849
4850 // Dispatch pointer down events using the new pointer locations.
4851 while (!downIdBits.isEmpty()) {
4852 uint32_t downId = downIdBits.clearFirstMarkedBit();
4853 dispatchedIdBits.markBit(downId);
4854
4855 if (dispatchedIdBits.count() == 1) {
4856 // First pointer is going down. Set down time.
4857 mDownTime = when;
4858 }
4859
4860 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004861 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004862 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004863 mCurrentCookedState.cookedPointerData.pointerProperties,
4864 mCurrentCookedState.cookedPointerData.pointerCoords,
4865 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004866 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868 }
4869}
4870
4871void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4872 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004873 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4874 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 int32_t metaState = getContext()->getGlobalMetaState();
4876 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004877 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004878 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004879 mLastCookedState.cookedPointerData.pointerProperties,
4880 mLastCookedState.cookedPointerData.pointerCoords,
4881 mLastCookedState.cookedPointerData.idToIndex,
4882 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004883 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4884 mSentHoverEnter = false;
4885 }
4886}
4887
4888void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004889 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4890 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004891 int32_t metaState = getContext()->getGlobalMetaState();
4892 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004893 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004894 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004895 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004896 mCurrentCookedState.cookedPointerData.pointerProperties,
4897 mCurrentCookedState.cookedPointerData.pointerCoords,
4898 mCurrentCookedState.cookedPointerData.idToIndex,
4899 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004900 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4901 mSentHoverEnter = true;
4902 }
4903
4904 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004905 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004906 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004907 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004908 mCurrentCookedState.cookedPointerData.pointerProperties,
4909 mCurrentCookedState.cookedPointerData.pointerCoords,
4910 mCurrentCookedState.cookedPointerData.idToIndex,
4911 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004912 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4913 }
4914}
4915
Michael Wright7b159c92015-05-14 14:48:03 +01004916void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4917 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4918 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4919 const int32_t metaState = getContext()->getGlobalMetaState();
4920 int32_t buttonState = mLastCookedState.buttonState;
4921 while (!releasedButtons.isEmpty()) {
4922 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4923 buttonState &= ~actionButton;
4924 dispatchMotion(when, policyFlags, mSource,
4925 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4926 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004927 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004928 mCurrentCookedState.cookedPointerData.pointerProperties,
4929 mCurrentCookedState.cookedPointerData.pointerCoords,
4930 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4931 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4932 }
4933}
4934
4935void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4936 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4937 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4938 const int32_t metaState = getContext()->getGlobalMetaState();
4939 int32_t buttonState = mLastCookedState.buttonState;
4940 while (!pressedButtons.isEmpty()) {
4941 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4942 buttonState |= actionButton;
4943 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4944 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004945 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004946 mCurrentCookedState.cookedPointerData.pointerProperties,
4947 mCurrentCookedState.cookedPointerData.pointerCoords,
4948 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4949 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4950 }
4951}
4952
4953const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4954 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4955 return cookedPointerData.touchingIdBits;
4956 }
4957 return cookedPointerData.hoveringIdBits;
4958}
4959
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004961 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004962
Michael Wright842500e2015-03-13 17:32:02 -07004963 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004964 mCurrentCookedState.deviceTimestamp =
4965 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004966 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4967 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4968 mCurrentRawState.rawPointerData.hoveringIdBits;
4969 mCurrentCookedState.cookedPointerData.touchingIdBits =
4970 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971
Michael Wright7b159c92015-05-14 14:48:03 +01004972 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4973 mCurrentCookedState.buttonState = 0;
4974 } else {
4975 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4976 }
4977
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 // Walk through the the active pointers and map device coordinates onto
4979 // surface coordinates and adjust for display orientation.
4980 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004981 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004982
4983 // Size
4984 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4985 switch (mCalibration.sizeCalibration) {
4986 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4987 case Calibration::SIZE_CALIBRATION_DIAMETER:
4988 case Calibration::SIZE_CALIBRATION_BOX:
4989 case Calibration::SIZE_CALIBRATION_AREA:
4990 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4991 touchMajor = in.touchMajor;
4992 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4993 toolMajor = in.toolMajor;
4994 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4995 size = mRawPointerAxes.touchMinor.valid
4996 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4997 } else if (mRawPointerAxes.touchMajor.valid) {
4998 toolMajor = touchMajor = in.touchMajor;
4999 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
5000 ? in.touchMinor : in.touchMajor;
5001 size = mRawPointerAxes.touchMinor.valid
5002 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5003 } else if (mRawPointerAxes.toolMajor.valid) {
5004 touchMajor = toolMajor = in.toolMajor;
5005 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5006 ? in.toolMinor : in.toolMajor;
5007 size = mRawPointerAxes.toolMinor.valid
5008 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5009 } else {
5010 ALOG_ASSERT(false, "No touch or tool axes. "
5011 "Size calibration should have been resolved to NONE.");
5012 touchMajor = 0;
5013 touchMinor = 0;
5014 toolMajor = 0;
5015 toolMinor = 0;
5016 size = 0;
5017 }
5018
5019 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005020 uint32_t touchingCount =
5021 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005022 if (touchingCount > 1) {
5023 touchMajor /= touchingCount;
5024 touchMinor /= touchingCount;
5025 toolMajor /= touchingCount;
5026 toolMinor /= touchingCount;
5027 size /= touchingCount;
5028 }
5029 }
5030
5031 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5032 touchMajor *= mGeometricScale;
5033 touchMinor *= mGeometricScale;
5034 toolMajor *= mGeometricScale;
5035 toolMinor *= mGeometricScale;
5036 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5037 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5038 touchMinor = touchMajor;
5039 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5040 toolMinor = toolMajor;
5041 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5042 touchMinor = touchMajor;
5043 toolMinor = toolMajor;
5044 }
5045
5046 mCalibration.applySizeScaleAndBias(&touchMajor);
5047 mCalibration.applySizeScaleAndBias(&touchMinor);
5048 mCalibration.applySizeScaleAndBias(&toolMajor);
5049 mCalibration.applySizeScaleAndBias(&toolMinor);
5050 size *= mSizeScale;
5051 break;
5052 default:
5053 touchMajor = 0;
5054 touchMinor = 0;
5055 toolMajor = 0;
5056 toolMinor = 0;
5057 size = 0;
5058 break;
5059 }
5060
5061 // Pressure
5062 float pressure;
5063 switch (mCalibration.pressureCalibration) {
5064 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5065 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5066 pressure = in.pressure * mPressureScale;
5067 break;
5068 default:
5069 pressure = in.isHovering ? 0 : 1;
5070 break;
5071 }
5072
5073 // Tilt and Orientation
5074 float tilt;
5075 float orientation;
5076 if (mHaveTilt) {
5077 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5078 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5079 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5080 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5081 } else {
5082 tilt = 0;
5083
5084 switch (mCalibration.orientationCalibration) {
5085 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5086 orientation = in.orientation * mOrientationScale;
5087 break;
5088 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5089 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5090 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5091 if (c1 != 0 || c2 != 0) {
5092 orientation = atan2f(c1, c2) * 0.5f;
5093 float confidence = hypotf(c1, c2);
5094 float scale = 1.0f + confidence / 16.0f;
5095 touchMajor *= scale;
5096 touchMinor /= scale;
5097 toolMajor *= scale;
5098 toolMinor /= scale;
5099 } else {
5100 orientation = 0;
5101 }
5102 break;
5103 }
5104 default:
5105 orientation = 0;
5106 }
5107 }
5108
5109 // Distance
5110 float distance;
5111 switch (mCalibration.distanceCalibration) {
5112 case Calibration::DISTANCE_CALIBRATION_SCALED:
5113 distance = in.distance * mDistanceScale;
5114 break;
5115 default:
5116 distance = 0;
5117 }
5118
5119 // Coverage
5120 int32_t rawLeft, rawTop, rawRight, rawBottom;
5121 switch (mCalibration.coverageCalibration) {
5122 case Calibration::COVERAGE_CALIBRATION_BOX:
5123 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5124 rawRight = in.toolMinor & 0x0000ffff;
5125 rawBottom = in.toolMajor & 0x0000ffff;
5126 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5127 break;
5128 default:
5129 rawLeft = rawTop = rawRight = rawBottom = 0;
5130 break;
5131 }
5132
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005133 // Adjust X,Y coords for device calibration
5134 // TODO: Adjust coverage coords?
5135 float xTransformed = in.x, yTransformed = in.y;
5136 mAffineTransform.applyTo(xTransformed, yTransformed);
5137
5138 // Adjust X, Y, and coverage coords for surface orientation.
5139 float x, y;
5140 float left, top, right, bottom;
5141
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 switch (mSurfaceOrientation) {
5143 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005144 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5145 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5147 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5148 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5149 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5150 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005151 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5153 }
5154 break;
5155 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005156 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005157 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005158 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5159 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5161 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5162 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005163 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5165 }
5166 break;
5167 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005168 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005169 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005170 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5171 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5173 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5174 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005175 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5177 }
5178 break;
5179 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005180 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5181 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5183 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5184 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5185 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5186 break;
5187 }
5188
5189 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005190 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 out.clear();
5192 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5194 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5195 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5196 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5197 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5198 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5199 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5200 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5201 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5202 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5203 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5204 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5205 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5206 } else {
5207 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5208 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5209 }
5210
5211 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005212 PointerProperties& properties =
5213 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 uint32_t id = in.id;
5215 properties.clear();
5216 properties.id = id;
5217 properties.toolType = in.toolType;
5218
5219 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005220 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 }
5222}
5223
5224void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5225 PointerUsage pointerUsage) {
5226 if (pointerUsage != mPointerUsage) {
5227 abortPointerUsage(when, policyFlags);
5228 mPointerUsage = pointerUsage;
5229 }
5230
5231 switch (mPointerUsage) {
5232 case POINTER_USAGE_GESTURES:
5233 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5234 break;
5235 case POINTER_USAGE_STYLUS:
5236 dispatchPointerStylus(when, policyFlags);
5237 break;
5238 case POINTER_USAGE_MOUSE:
5239 dispatchPointerMouse(when, policyFlags);
5240 break;
5241 default:
5242 break;
5243 }
5244}
5245
5246void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5247 switch (mPointerUsage) {
5248 case POINTER_USAGE_GESTURES:
5249 abortPointerGestures(when, policyFlags);
5250 break;
5251 case POINTER_USAGE_STYLUS:
5252 abortPointerStylus(when, policyFlags);
5253 break;
5254 case POINTER_USAGE_MOUSE:
5255 abortPointerMouse(when, policyFlags);
5256 break;
5257 default:
5258 break;
5259 }
5260
5261 mPointerUsage = POINTER_USAGE_NONE;
5262}
5263
5264void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5265 bool isTimeout) {
5266 // Update current gesture coordinates.
5267 bool cancelPreviousGesture, finishPreviousGesture;
5268 bool sendEvents = preparePointerGestures(when,
5269 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5270 if (!sendEvents) {
5271 return;
5272 }
5273 if (finishPreviousGesture) {
5274 cancelPreviousGesture = false;
5275 }
5276
5277 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005278 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5279 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005280 if (finishPreviousGesture || cancelPreviousGesture) {
5281 mPointerController->clearSpots();
5282 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005283
5284 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5285 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5286 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005287 mPointerGesture.currentGestureIdBits,
5288 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005289 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005290 } else {
5291 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5292 }
5293
5294 // Show or hide the pointer if needed.
5295 switch (mPointerGesture.currentGestureMode) {
5296 case PointerGesture::NEUTRAL:
5297 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005298 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5299 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 // Remind the user of where the pointer is after finishing a gesture with spots.
5301 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5302 }
5303 break;
5304 case PointerGesture::TAP:
5305 case PointerGesture::TAP_DRAG:
5306 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5307 case PointerGesture::HOVER:
5308 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005309 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 // Unfade the pointer when the current gesture manipulates the
5311 // area directly under the pointer.
5312 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5313 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314 case PointerGesture::FREEFORM:
5315 // Fade the pointer when the current gesture manipulates a different
5316 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005317 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005318 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5319 } else {
5320 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5321 }
5322 break;
5323 }
5324
5325 // Send events!
5326 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005327 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005328
5329 // Update last coordinates of pointers that have moved so that we observe the new
5330 // pointer positions at the same time as other pointers that have just gone up.
5331 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5332 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5333 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5334 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5335 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5336 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5337 bool moveNeeded = false;
5338 if (down && !cancelPreviousGesture && !finishPreviousGesture
5339 && !mPointerGesture.lastGestureIdBits.isEmpty()
5340 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5341 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5342 & mPointerGesture.lastGestureIdBits.value);
5343 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5344 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5345 mPointerGesture.lastGestureProperties,
5346 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5347 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005348 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 moveNeeded = true;
5350 }
5351 }
5352
5353 // Send motion events for all pointers that went up or were canceled.
5354 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5355 if (!dispatchedGestureIdBits.isEmpty()) {
5356 if (cancelPreviousGesture) {
5357 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005358 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005359 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005360 mPointerGesture.lastGestureProperties,
5361 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005362 dispatchedGestureIdBits, -1, 0,
5363 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005364
5365 dispatchedGestureIdBits.clear();
5366 } else {
5367 BitSet32 upGestureIdBits;
5368 if (finishPreviousGesture) {
5369 upGestureIdBits = dispatchedGestureIdBits;
5370 } else {
5371 upGestureIdBits.value = dispatchedGestureIdBits.value
5372 & ~mPointerGesture.currentGestureIdBits.value;
5373 }
5374 while (!upGestureIdBits.isEmpty()) {
5375 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5376
5377 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005378 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005380 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005381 mPointerGesture.lastGestureProperties,
5382 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5383 dispatchedGestureIdBits, id,
5384 0, 0, mPointerGesture.downTime);
5385
5386 dispatchedGestureIdBits.clearBit(id);
5387 }
5388 }
5389 }
5390
5391 // Send motion events for all pointers that moved.
5392 if (moveNeeded) {
5393 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005394 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005395 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005396 mPointerGesture.currentGestureProperties,
5397 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5398 dispatchedGestureIdBits, -1,
5399 0, 0, mPointerGesture.downTime);
5400 }
5401
5402 // Send motion events for all pointers that went down.
5403 if (down) {
5404 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5405 & ~dispatchedGestureIdBits.value);
5406 while (!downGestureIdBits.isEmpty()) {
5407 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5408 dispatchedGestureIdBits.markBit(id);
5409
5410 if (dispatchedGestureIdBits.count() == 1) {
5411 mPointerGesture.downTime = when;
5412 }
5413
5414 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005415 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005416 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005417 mPointerGesture.currentGestureProperties,
5418 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5419 dispatchedGestureIdBits, id,
5420 0, 0, mPointerGesture.downTime);
5421 }
5422 }
5423
5424 // Send motion events for hover.
5425 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5426 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005427 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005428 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005429 mPointerGesture.currentGestureProperties,
5430 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5431 mPointerGesture.currentGestureIdBits, -1,
5432 0, 0, mPointerGesture.downTime);
5433 } else if (dispatchedGestureIdBits.isEmpty()
5434 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5435 // Synthesize a hover move event after all pointers go up to indicate that
5436 // the pointer is hovering again even if the user is not currently touching
5437 // the touch pad. This ensures that a view will receive a fresh hover enter
5438 // event after a tap.
5439 float x, y;
5440 mPointerController->getPosition(&x, &y);
5441
5442 PointerProperties pointerProperties;
5443 pointerProperties.clear();
5444 pointerProperties.id = 0;
5445 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5446
5447 PointerCoords pointerCoords;
5448 pointerCoords.clear();
5449 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5450 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5451
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005452 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005453 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005454 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005455 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005456 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005457 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005458 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005459 getListener()->notifyMotion(&args);
5460 }
5461
5462 // Update state.
5463 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5464 if (!down) {
5465 mPointerGesture.lastGestureIdBits.clear();
5466 } else {
5467 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5468 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5469 uint32_t id = idBits.clearFirstMarkedBit();
5470 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5471 mPointerGesture.lastGestureProperties[index].copyFrom(
5472 mPointerGesture.currentGestureProperties[index]);
5473 mPointerGesture.lastGestureCoords[index].copyFrom(
5474 mPointerGesture.currentGestureCoords[index]);
5475 mPointerGesture.lastGestureIdToIndex[id] = index;
5476 }
5477 }
5478}
5479
5480void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5481 // Cancel previously dispatches pointers.
5482 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5483 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005484 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005486 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005487 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 mPointerGesture.lastGestureProperties,
5489 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5490 mPointerGesture.lastGestureIdBits, -1,
5491 0, 0, mPointerGesture.downTime);
5492 }
5493
5494 // Reset the current pointer gesture.
5495 mPointerGesture.reset();
5496 mPointerVelocityControl.reset();
5497
5498 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005499 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5501 mPointerController->clearSpots();
5502 }
5503}
5504
5505bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5506 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5507 *outCancelPreviousGesture = false;
5508 *outFinishPreviousGesture = false;
5509
5510 // Handle TAP timeout.
5511 if (isTimeout) {
5512#if DEBUG_GESTURES
5513 ALOGD("Gestures: Processing timeout");
5514#endif
5515
5516 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5517 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5518 // The tap/drag timeout has not yet expired.
5519 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5520 + mConfig.pointerGestureTapDragInterval);
5521 } else {
5522 // The tap is finished.
5523#if DEBUG_GESTURES
5524 ALOGD("Gestures: TAP finished");
5525#endif
5526 *outFinishPreviousGesture = true;
5527
5528 mPointerGesture.activeGestureId = -1;
5529 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5530 mPointerGesture.currentGestureIdBits.clear();
5531
5532 mPointerVelocityControl.reset();
5533 return true;
5534 }
5535 }
5536
5537 // We did not handle this timeout.
5538 return false;
5539 }
5540
Michael Wright842500e2015-03-13 17:32:02 -07005541 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5542 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543
5544 // Update the velocity tracker.
5545 {
5546 VelocityTracker::Position positions[MAX_POINTERS];
5547 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005548 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005549 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005550 const RawPointerData::Pointer& pointer =
5551 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005552 positions[count].x = pointer.x * mPointerXMovementScale;
5553 positions[count].y = pointer.y * mPointerYMovementScale;
5554 }
5555 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005556 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 }
5558
5559 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5560 // to NEUTRAL, then we should not generate tap event.
5561 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5562 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5563 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5564 mPointerGesture.resetTap();
5565 }
5566
5567 // Pick a new active touch id if needed.
5568 // Choose an arbitrary pointer that just went down, if there is one.
5569 // Otherwise choose an arbitrary remaining pointer.
5570 // This guarantees we always have an active touch id when there is at least one pointer.
5571 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5573 int32_t activeTouchId = lastActiveTouchId;
5574 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005575 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005576 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005577 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 mPointerGesture.firstTouchTime = when;
5579 }
Michael Wright842500e2015-03-13 17:32:02 -07005580 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005581 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005583 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 } else {
5585 activeTouchId = mPointerGesture.activeTouchId = -1;
5586 }
5587 }
5588
5589 // Determine whether we are in quiet time.
5590 bool isQuietTime = false;
5591 if (activeTouchId < 0) {
5592 mPointerGesture.resetQuietTime();
5593 } else {
5594 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5595 if (!isQuietTime) {
5596 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5597 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5598 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5599 && currentFingerCount < 2) {
5600 // Enter quiet time when exiting swipe or freeform state.
5601 // This is to prevent accidentally entering the hover state and flinging the
5602 // pointer when finishing a swipe and there is still one pointer left onscreen.
5603 isQuietTime = true;
5604 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5605 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005606 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 // Enter quiet time when releasing the button and there are still two or more
5608 // fingers down. This may indicate that one finger was used to press the button
5609 // but it has not gone up yet.
5610 isQuietTime = true;
5611 }
5612 if (isQuietTime) {
5613 mPointerGesture.quietTime = when;
5614 }
5615 }
5616 }
5617
5618 // Switch states based on button and pointer state.
5619 if (isQuietTime) {
5620 // Case 1: Quiet time. (QUIET)
5621#if DEBUG_GESTURES
5622 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5623 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5624#endif
5625 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5626 *outFinishPreviousGesture = true;
5627 }
5628
5629 mPointerGesture.activeGestureId = -1;
5630 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5631 mPointerGesture.currentGestureIdBits.clear();
5632
5633 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005634 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005635 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5636 // The pointer follows the active touch point.
5637 // Emit DOWN, MOVE, UP events at the pointer location.
5638 //
5639 // Only the active touch matters; other fingers are ignored. This policy helps
5640 // to handle the case where the user places a second finger on the touch pad
5641 // to apply the necessary force to depress an integrated button below the surface.
5642 // We don't want the second finger to be delivered to applications.
5643 //
5644 // For this to work well, we need to make sure to track the pointer that is really
5645 // active. If the user first puts one finger down to click then adds another
5646 // finger to drag then the active pointer should switch to the finger that is
5647 // being dragged.
5648#if DEBUG_GESTURES
5649 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5650 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5651#endif
5652 // Reset state when just starting.
5653 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5654 *outFinishPreviousGesture = true;
5655 mPointerGesture.activeGestureId = 0;
5656 }
5657
5658 // Switch pointers if needed.
5659 // Find the fastest pointer and follow it.
5660 if (activeTouchId >= 0 && currentFingerCount > 1) {
5661 int32_t bestId = -1;
5662 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005663 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 uint32_t id = idBits.clearFirstMarkedBit();
5665 float vx, vy;
5666 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5667 float speed = hypotf(vx, vy);
5668 if (speed > bestSpeed) {
5669 bestId = id;
5670 bestSpeed = speed;
5671 }
5672 }
5673 }
5674 if (bestId >= 0 && bestId != activeTouchId) {
5675 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676#if DEBUG_GESTURES
5677 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5678 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5679#endif
5680 }
5681 }
5682
Jun Mukaifa1706a2015-12-03 01:14:46 -08005683 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005684 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005685 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005686 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005687 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005688 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005689 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5690 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005691
5692 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5693 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5694
5695 // Move the pointer using a relative motion.
5696 // When using spots, the click will occur at the position of the anchor
5697 // spot and all other spots will move there.
5698 mPointerController->move(deltaX, deltaY);
5699 } else {
5700 mPointerVelocityControl.reset();
5701 }
5702
5703 float x, y;
5704 mPointerController->getPosition(&x, &y);
5705
5706 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5707 mPointerGesture.currentGestureIdBits.clear();
5708 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5709 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5710 mPointerGesture.currentGestureProperties[0].clear();
5711 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5712 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5713 mPointerGesture.currentGestureCoords[0].clear();
5714 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5715 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5716 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5717 } else if (currentFingerCount == 0) {
5718 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5719 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5720 *outFinishPreviousGesture = true;
5721 }
5722
5723 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5724 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5725 bool tapped = false;
5726 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5727 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5728 && lastFingerCount == 1) {
5729 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5730 float x, y;
5731 mPointerController->getPosition(&x, &y);
5732 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5733 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5734#if DEBUG_GESTURES
5735 ALOGD("Gestures: TAP");
5736#endif
5737
5738 mPointerGesture.tapUpTime = when;
5739 getContext()->requestTimeoutAtTime(when
5740 + mConfig.pointerGestureTapDragInterval);
5741
5742 mPointerGesture.activeGestureId = 0;
5743 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5744 mPointerGesture.currentGestureIdBits.clear();
5745 mPointerGesture.currentGestureIdBits.markBit(
5746 mPointerGesture.activeGestureId);
5747 mPointerGesture.currentGestureIdToIndex[
5748 mPointerGesture.activeGestureId] = 0;
5749 mPointerGesture.currentGestureProperties[0].clear();
5750 mPointerGesture.currentGestureProperties[0].id =
5751 mPointerGesture.activeGestureId;
5752 mPointerGesture.currentGestureProperties[0].toolType =
5753 AMOTION_EVENT_TOOL_TYPE_FINGER;
5754 mPointerGesture.currentGestureCoords[0].clear();
5755 mPointerGesture.currentGestureCoords[0].setAxisValue(
5756 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5757 mPointerGesture.currentGestureCoords[0].setAxisValue(
5758 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5759 mPointerGesture.currentGestureCoords[0].setAxisValue(
5760 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5761
5762 tapped = true;
5763 } else {
5764#if DEBUG_GESTURES
5765 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5766 x - mPointerGesture.tapX,
5767 y - mPointerGesture.tapY);
5768#endif
5769 }
5770 } else {
5771#if DEBUG_GESTURES
5772 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5773 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5774 (when - mPointerGesture.tapDownTime) * 0.000001f);
5775 } else {
5776 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5777 }
5778#endif
5779 }
5780 }
5781
5782 mPointerVelocityControl.reset();
5783
5784 if (!tapped) {
5785#if DEBUG_GESTURES
5786 ALOGD("Gestures: NEUTRAL");
5787#endif
5788 mPointerGesture.activeGestureId = -1;
5789 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5790 mPointerGesture.currentGestureIdBits.clear();
5791 }
5792 } else if (currentFingerCount == 1) {
5793 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5794 // The pointer follows the active touch point.
5795 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5796 // When in TAP_DRAG, emit MOVE events at the pointer location.
5797 ALOG_ASSERT(activeTouchId >= 0);
5798
5799 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5800 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5801 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5802 float x, y;
5803 mPointerController->getPosition(&x, &y);
5804 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5805 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5806 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5807 } else {
5808#if DEBUG_GESTURES
5809 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5810 x - mPointerGesture.tapX,
5811 y - mPointerGesture.tapY);
5812#endif
5813 }
5814 } else {
5815#if DEBUG_GESTURES
5816 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5817 (when - mPointerGesture.tapUpTime) * 0.000001f);
5818#endif
5819 }
5820 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5821 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5822 }
5823
Jun Mukaifa1706a2015-12-03 01:14:46 -08005824 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005825 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005826 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005827 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005828 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005829 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005830 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5831 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005832
5833 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5834 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5835
5836 // Move the pointer using a relative motion.
5837 // When using spots, the hover or drag will occur at the position of the anchor spot.
5838 mPointerController->move(deltaX, deltaY);
5839 } else {
5840 mPointerVelocityControl.reset();
5841 }
5842
5843 bool down;
5844 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5845#if DEBUG_GESTURES
5846 ALOGD("Gestures: TAP_DRAG");
5847#endif
5848 down = true;
5849 } else {
5850#if DEBUG_GESTURES
5851 ALOGD("Gestures: HOVER");
5852#endif
5853 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5854 *outFinishPreviousGesture = true;
5855 }
5856 mPointerGesture.activeGestureId = 0;
5857 down = false;
5858 }
5859
5860 float x, y;
5861 mPointerController->getPosition(&x, &y);
5862
5863 mPointerGesture.currentGestureIdBits.clear();
5864 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5865 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5866 mPointerGesture.currentGestureProperties[0].clear();
5867 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5868 mPointerGesture.currentGestureProperties[0].toolType =
5869 AMOTION_EVENT_TOOL_TYPE_FINGER;
5870 mPointerGesture.currentGestureCoords[0].clear();
5871 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5872 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5873 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5874 down ? 1.0f : 0.0f);
5875
5876 if (lastFingerCount == 0 && currentFingerCount != 0) {
5877 mPointerGesture.resetTap();
5878 mPointerGesture.tapDownTime = when;
5879 mPointerGesture.tapX = x;
5880 mPointerGesture.tapY = y;
5881 }
5882 } else {
5883 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5884 // We need to provide feedback for each finger that goes down so we cannot wait
5885 // for the fingers to move before deciding what to do.
5886 //
5887 // The ambiguous case is deciding what to do when there are two fingers down but they
5888 // have not moved enough to determine whether they are part of a drag or part of a
5889 // freeform gesture, or just a press or long-press at the pointer location.
5890 //
5891 // When there are two fingers we start with the PRESS hypothesis and we generate a
5892 // down at the pointer location.
5893 //
5894 // When the two fingers move enough or when additional fingers are added, we make
5895 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5896 ALOG_ASSERT(activeTouchId >= 0);
5897
5898 bool settled = when >= mPointerGesture.firstTouchTime
5899 + mConfig.pointerGestureMultitouchSettleInterval;
5900 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5901 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5902 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5903 *outFinishPreviousGesture = true;
5904 } else if (!settled && currentFingerCount > lastFingerCount) {
5905 // Additional pointers have gone down but not yet settled.
5906 // Reset the gesture.
5907#if DEBUG_GESTURES
5908 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5909 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5910 + mConfig.pointerGestureMultitouchSettleInterval - when)
5911 * 0.000001f);
5912#endif
5913 *outCancelPreviousGesture = true;
5914 } else {
5915 // Continue previous gesture.
5916 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5917 }
5918
5919 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5920 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5921 mPointerGesture.activeGestureId = 0;
5922 mPointerGesture.referenceIdBits.clear();
5923 mPointerVelocityControl.reset();
5924
5925 // Use the centroid and pointer location as the reference points for the gesture.
5926#if DEBUG_GESTURES
5927 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5928 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5929 + mConfig.pointerGestureMultitouchSettleInterval - when)
5930 * 0.000001f);
5931#endif
Michael Wright842500e2015-03-13 17:32:02 -07005932 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005933 &mPointerGesture.referenceTouchX,
5934 &mPointerGesture.referenceTouchY);
5935 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5936 &mPointerGesture.referenceGestureY);
5937 }
5938
5939 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005940 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5942 uint32_t id = idBits.clearFirstMarkedBit();
5943 mPointerGesture.referenceDeltas[id].dx = 0;
5944 mPointerGesture.referenceDeltas[id].dy = 0;
5945 }
Michael Wright842500e2015-03-13 17:32:02 -07005946 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947
5948 // Add delta for all fingers and calculate a common movement delta.
5949 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005950 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5951 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5953 bool first = (idBits == commonIdBits);
5954 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005955 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5956 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005957 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5958 delta.dx += cpd.x - lpd.x;
5959 delta.dy += cpd.y - lpd.y;
5960
5961 if (first) {
5962 commonDeltaX = delta.dx;
5963 commonDeltaY = delta.dy;
5964 } else {
5965 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5966 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5967 }
5968 }
5969
5970 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5971 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5972 float dist[MAX_POINTER_ID + 1];
5973 int32_t distOverThreshold = 0;
5974 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5975 uint32_t id = idBits.clearFirstMarkedBit();
5976 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5977 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5978 delta.dy * mPointerYZoomScale);
5979 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5980 distOverThreshold += 1;
5981 }
5982 }
5983
5984 // Only transition when at least two pointers have moved further than
5985 // the minimum distance threshold.
5986 if (distOverThreshold >= 2) {
5987 if (currentFingerCount > 2) {
5988 // There are more than two pointers, switch to FREEFORM.
5989#if DEBUG_GESTURES
5990 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5991 currentFingerCount);
5992#endif
5993 *outCancelPreviousGesture = true;
5994 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5995 } else {
5996 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005997 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998 uint32_t id1 = idBits.clearFirstMarkedBit();
5999 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07006000 const RawPointerData::Pointer& p1 =
6001 mCurrentRawState.rawPointerData.pointerForId(id1);
6002 const RawPointerData::Pointer& p2 =
6003 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006004 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6005 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6006 // There are two pointers but they are too far apart for a SWIPE,
6007 // switch to FREEFORM.
6008#if DEBUG_GESTURES
6009 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6010 mutualDistance, mPointerGestureMaxSwipeWidth);
6011#endif
6012 *outCancelPreviousGesture = true;
6013 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6014 } else {
6015 // There are two pointers. Wait for both pointers to start moving
6016 // before deciding whether this is a SWIPE or FREEFORM gesture.
6017 float dist1 = dist[id1];
6018 float dist2 = dist[id2];
6019 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6020 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6021 // Calculate the dot product of the displacement vectors.
6022 // When the vectors are oriented in approximately the same direction,
6023 // the angle betweeen them is near zero and the cosine of the angle
6024 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6025 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6026 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6027 float dx1 = delta1.dx * mPointerXZoomScale;
6028 float dy1 = delta1.dy * mPointerYZoomScale;
6029 float dx2 = delta2.dx * mPointerXZoomScale;
6030 float dy2 = delta2.dy * mPointerYZoomScale;
6031 float dot = dx1 * dx2 + dy1 * dy2;
6032 float cosine = dot / (dist1 * dist2); // denominator always > 0
6033 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6034 // Pointers are moving in the same direction. Switch to SWIPE.
6035#if DEBUG_GESTURES
6036 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6037 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6038 "cosine %0.3f >= %0.3f",
6039 dist1, mConfig.pointerGestureMultitouchMinDistance,
6040 dist2, mConfig.pointerGestureMultitouchMinDistance,
6041 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6042#endif
6043 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6044 } else {
6045 // Pointers are moving in different directions. Switch to FREEFORM.
6046#if DEBUG_GESTURES
6047 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6048 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6049 "cosine %0.3f < %0.3f",
6050 dist1, mConfig.pointerGestureMultitouchMinDistance,
6051 dist2, mConfig.pointerGestureMultitouchMinDistance,
6052 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6053#endif
6054 *outCancelPreviousGesture = true;
6055 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6056 }
6057 }
6058 }
6059 }
6060 }
6061 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6062 // Switch from SWIPE to FREEFORM if additional pointers go down.
6063 // Cancel previous gesture.
6064 if (currentFingerCount > 2) {
6065#if DEBUG_GESTURES
6066 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6067 currentFingerCount);
6068#endif
6069 *outCancelPreviousGesture = true;
6070 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6071 }
6072 }
6073
6074 // Move the reference points based on the overall group motion of the fingers
6075 // except in PRESS mode while waiting for a transition to occur.
6076 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6077 && (commonDeltaX || commonDeltaY)) {
6078 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6079 uint32_t id = idBits.clearFirstMarkedBit();
6080 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6081 delta.dx = 0;
6082 delta.dy = 0;
6083 }
6084
6085 mPointerGesture.referenceTouchX += commonDeltaX;
6086 mPointerGesture.referenceTouchY += commonDeltaY;
6087
6088 commonDeltaX *= mPointerXMovementScale;
6089 commonDeltaY *= mPointerYMovementScale;
6090
6091 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6092 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6093
6094 mPointerGesture.referenceGestureX += commonDeltaX;
6095 mPointerGesture.referenceGestureY += commonDeltaY;
6096 }
6097
6098 // Report gestures.
6099 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6100 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6101 // PRESS or SWIPE mode.
6102#if DEBUG_GESTURES
6103 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6104 "activeGestureId=%d, currentTouchPointerCount=%d",
6105 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6106#endif
6107 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6108
6109 mPointerGesture.currentGestureIdBits.clear();
6110 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6111 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6112 mPointerGesture.currentGestureProperties[0].clear();
6113 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6114 mPointerGesture.currentGestureProperties[0].toolType =
6115 AMOTION_EVENT_TOOL_TYPE_FINGER;
6116 mPointerGesture.currentGestureCoords[0].clear();
6117 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6118 mPointerGesture.referenceGestureX);
6119 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6120 mPointerGesture.referenceGestureY);
6121 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6122 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6123 // FREEFORM mode.
6124#if DEBUG_GESTURES
6125 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6126 "activeGestureId=%d, currentTouchPointerCount=%d",
6127 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6128#endif
6129 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6130
6131 mPointerGesture.currentGestureIdBits.clear();
6132
6133 BitSet32 mappedTouchIdBits;
6134 BitSet32 usedGestureIdBits;
6135 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6136 // Initially, assign the active gesture id to the active touch point
6137 // if there is one. No other touch id bits are mapped yet.
6138 if (!*outCancelPreviousGesture) {
6139 mappedTouchIdBits.markBit(activeTouchId);
6140 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6141 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6142 mPointerGesture.activeGestureId;
6143 } else {
6144 mPointerGesture.activeGestureId = -1;
6145 }
6146 } else {
6147 // Otherwise, assume we mapped all touches from the previous frame.
6148 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006149 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6150 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006151 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6152
6153 // Check whether we need to choose a new active gesture id because the
6154 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006155 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6156 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006157 !upTouchIdBits.isEmpty(); ) {
6158 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6159 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6160 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6161 mPointerGesture.activeGestureId = -1;
6162 break;
6163 }
6164 }
6165 }
6166
6167#if DEBUG_GESTURES
6168 ALOGD("Gestures: FREEFORM follow up "
6169 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6170 "activeGestureId=%d",
6171 mappedTouchIdBits.value, usedGestureIdBits.value,
6172 mPointerGesture.activeGestureId);
6173#endif
6174
Michael Wright842500e2015-03-13 17:32:02 -07006175 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176 for (uint32_t i = 0; i < currentFingerCount; i++) {
6177 uint32_t touchId = idBits.clearFirstMarkedBit();
6178 uint32_t gestureId;
6179 if (!mappedTouchIdBits.hasBit(touchId)) {
6180 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6181 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6182#if DEBUG_GESTURES
6183 ALOGD("Gestures: FREEFORM "
6184 "new mapping for touch id %d -> gesture id %d",
6185 touchId, gestureId);
6186#endif
6187 } else {
6188 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6189#if DEBUG_GESTURES
6190 ALOGD("Gestures: FREEFORM "
6191 "existing mapping for touch id %d -> gesture id %d",
6192 touchId, gestureId);
6193#endif
6194 }
6195 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6196 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6197
6198 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006199 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006200 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6201 * mPointerXZoomScale;
6202 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6203 * mPointerYZoomScale;
6204 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6205
6206 mPointerGesture.currentGestureProperties[i].clear();
6207 mPointerGesture.currentGestureProperties[i].id = gestureId;
6208 mPointerGesture.currentGestureProperties[i].toolType =
6209 AMOTION_EVENT_TOOL_TYPE_FINGER;
6210 mPointerGesture.currentGestureCoords[i].clear();
6211 mPointerGesture.currentGestureCoords[i].setAxisValue(
6212 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6213 mPointerGesture.currentGestureCoords[i].setAxisValue(
6214 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6215 mPointerGesture.currentGestureCoords[i].setAxisValue(
6216 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6217 }
6218
6219 if (mPointerGesture.activeGestureId < 0) {
6220 mPointerGesture.activeGestureId =
6221 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6222#if DEBUG_GESTURES
6223 ALOGD("Gestures: FREEFORM new "
6224 "activeGestureId=%d", mPointerGesture.activeGestureId);
6225#endif
6226 }
6227 }
6228 }
6229
Michael Wright842500e2015-03-13 17:32:02 -07006230 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231
6232#if DEBUG_GESTURES
6233 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6234 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6235 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6236 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6237 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6238 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6239 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6240 uint32_t id = idBits.clearFirstMarkedBit();
6241 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6242 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6243 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6244 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6245 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6246 id, index, properties.toolType,
6247 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6248 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6249 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6250 }
6251 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6252 uint32_t id = idBits.clearFirstMarkedBit();
6253 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6254 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6255 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6256 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6257 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6258 id, index, properties.toolType,
6259 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6260 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6261 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6262 }
6263#endif
6264 return true;
6265}
6266
6267void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6268 mPointerSimple.currentCoords.clear();
6269 mPointerSimple.currentProperties.clear();
6270
6271 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006272 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6273 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6274 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6275 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6276 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006277 mPointerController->setPosition(x, y);
6278
Michael Wright842500e2015-03-13 17:32:02 -07006279 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280 down = !hovering;
6281
6282 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006283 mPointerSimple.currentCoords.copyFrom(
6284 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6286 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6287 mPointerSimple.currentProperties.id = 0;
6288 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006289 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006290 } else {
6291 down = false;
6292 hovering = false;
6293 }
6294
6295 dispatchPointerSimple(when, policyFlags, down, hovering);
6296}
6297
6298void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6299 abortPointerSimple(when, policyFlags);
6300}
6301
6302void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6303 mPointerSimple.currentCoords.clear();
6304 mPointerSimple.currentProperties.clear();
6305
6306 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006307 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6308 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6309 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006310 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006311 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6312 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006313 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006314 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006315 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006316 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006317 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006318 * mPointerYMovementScale;
6319
6320 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6321 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6322
6323 mPointerController->move(deltaX, deltaY);
6324 } else {
6325 mPointerVelocityControl.reset();
6326 }
6327
Michael Wright842500e2015-03-13 17:32:02 -07006328 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329 hovering = !down;
6330
6331 float x, y;
6332 mPointerController->getPosition(&x, &y);
6333 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006334 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006335 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6336 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6337 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6338 hovering ? 0.0f : 1.0f);
6339 mPointerSimple.currentProperties.id = 0;
6340 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006341 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006342 } else {
6343 mPointerVelocityControl.reset();
6344
6345 down = false;
6346 hovering = false;
6347 }
6348
6349 dispatchPointerSimple(when, policyFlags, down, hovering);
6350}
6351
6352void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6353 abortPointerSimple(when, policyFlags);
6354
6355 mPointerVelocityControl.reset();
6356}
6357
6358void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6359 bool down, bool hovering) {
6360 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006361 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362
Yi Kong9b14ac62018-07-17 13:48:38 -07006363 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 if (down || hovering) {
6365 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6366 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006367 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6369 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6370 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6371 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006372 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 }
6374
6375 if (mPointerSimple.down && !down) {
6376 mPointerSimple.down = false;
6377
6378 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006379 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006380 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006381 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6382 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006383 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6384 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006385 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 getListener()->notifyMotion(&args);
6387 }
6388
6389 if (mPointerSimple.hovering && !hovering) {
6390 mPointerSimple.hovering = false;
6391
6392 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006393 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6394 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006395 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6396 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6398 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006399 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006400 getListener()->notifyMotion(&args);
6401 }
6402
6403 if (down) {
6404 if (!mPointerSimple.down) {
6405 mPointerSimple.down = true;
6406 mPointerSimple.downTime = when;
6407
6408 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006409 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6410 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006411 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6412 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006413 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006414 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6415 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006416 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006417 getListener()->notifyMotion(&args);
6418 }
6419
6420 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006421 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6422 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006423 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6424 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006425 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6426 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006427 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006428 getListener()->notifyMotion(&args);
6429 }
6430
6431 if (hovering) {
6432 if (!mPointerSimple.hovering) {
6433 mPointerSimple.hovering = true;
6434
6435 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006436 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6437 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006438 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006439 mCurrentRawState.buttonState, MotionClassification::NONE,
6440 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6442 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006443 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006444 getListener()->notifyMotion(&args);
6445 }
6446
6447 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006448 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6449 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006450 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006451 mCurrentRawState.buttonState, MotionClassification::NONE,
6452 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6454 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006455 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006456 getListener()->notifyMotion(&args);
6457 }
6458
Michael Wright842500e2015-03-13 17:32:02 -07006459 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6460 float vscroll = mCurrentRawState.rawVScroll;
6461 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006462 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6463 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006464
6465 // Send scroll.
6466 PointerCoords pointerCoords;
6467 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6468 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6469 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6470
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006471 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6472 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006473 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6474 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475 1, &mPointerSimple.currentProperties, &pointerCoords,
6476 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006477 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006478 getListener()->notifyMotion(&args);
6479 }
6480
6481 // Save state.
6482 if (down || hovering) {
6483 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6484 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6485 } else {
6486 mPointerSimple.reset();
6487 }
6488}
6489
6490void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6491 mPointerSimple.currentCoords.clear();
6492 mPointerSimple.currentProperties.clear();
6493
6494 dispatchPointerSimple(when, policyFlags, false, false);
6495}
6496
6497void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006498 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006499 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006500 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006501 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6502 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006503 PointerCoords pointerCoords[MAX_POINTERS];
6504 PointerProperties pointerProperties[MAX_POINTERS];
6505 uint32_t pointerCount = 0;
6506 while (!idBits.isEmpty()) {
6507 uint32_t id = idBits.clearFirstMarkedBit();
6508 uint32_t index = idToIndex[id];
6509 pointerProperties[pointerCount].copyFrom(properties[index]);
6510 pointerCoords[pointerCount].copyFrom(coords[index]);
6511
6512 if (changedId >= 0 && id == uint32_t(changedId)) {
6513 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6514 }
6515
6516 pointerCount += 1;
6517 }
6518
6519 ALOG_ASSERT(pointerCount != 0);
6520
6521 if (changedId >= 0 && pointerCount == 1) {
6522 // Replace initial down and final up action.
6523 // We can compare the action without masking off the changed pointer index
6524 // because we know the index is 0.
6525 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6526 action = AMOTION_EVENT_ACTION_DOWN;
6527 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6528 action = AMOTION_EVENT_ACTION_UP;
6529 } else {
6530 // Can't happen.
6531 ALOG_ASSERT(false);
6532 }
6533 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006534 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006535 const int32_t deviceId = getDeviceId();
6536 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006537 std::for_each(frames.begin(), frames.end(),
6538 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006539 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006540 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006541 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6542 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006543 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544 getListener()->notifyMotion(&args);
6545}
6546
6547bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6548 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6549 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6550 BitSet32 idBits) const {
6551 bool changed = false;
6552 while (!idBits.isEmpty()) {
6553 uint32_t id = idBits.clearFirstMarkedBit();
6554 uint32_t inIndex = inIdToIndex[id];
6555 uint32_t outIndex = outIdToIndex[id];
6556
6557 const PointerProperties& curInProperties = inProperties[inIndex];
6558 const PointerCoords& curInCoords = inCoords[inIndex];
6559 PointerProperties& curOutProperties = outProperties[outIndex];
6560 PointerCoords& curOutCoords = outCoords[outIndex];
6561
6562 if (curInProperties != curOutProperties) {
6563 curOutProperties.copyFrom(curInProperties);
6564 changed = true;
6565 }
6566
6567 if (curInCoords != curOutCoords) {
6568 curOutCoords.copyFrom(curInCoords);
6569 changed = true;
6570 }
6571 }
6572 return changed;
6573}
6574
6575void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006576 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006577 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6578 }
6579}
6580
Jeff Brownc9aa6282015-02-11 19:03:28 -08006581void TouchInputMapper::cancelTouch(nsecs_t when) {
6582 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006583 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006584}
6585
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006587 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006588 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006590 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6591 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6592 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593}
6594
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006595const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006596
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006597 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598#if DEBUG_VIRTUAL_KEYS
6599 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6600 "left=%d, top=%d, right=%d, bottom=%d",
6601 x, y,
6602 virtualKey.keyCode, virtualKey.scanCode,
6603 virtualKey.hitLeft, virtualKey.hitTop,
6604 virtualKey.hitRight, virtualKey.hitBottom);
6605#endif
6606
6607 if (virtualKey.isHit(x, y)) {
6608 return & virtualKey;
6609 }
6610 }
6611
Yi Kong9b14ac62018-07-17 13:48:38 -07006612 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613}
6614
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006615void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
6616 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
6617 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006619 current.rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620
6621 if (currentPointerCount == 0) {
6622 // No pointers to assign.
6623 return;
6624 }
6625
6626 if (lastPointerCount == 0) {
6627 // All pointers are new.
6628 for (uint32_t i = 0; i < currentPointerCount; i++) {
6629 uint32_t id = i;
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006630 current.rawPointerData.pointers[i].id = id;
6631 current.rawPointerData.idToIndex[id] = i;
6632 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006633 }
6634 return;
6635 }
6636
6637 if (currentPointerCount == 1 && lastPointerCount == 1
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006638 && current.rawPointerData.pointers[0].toolType
6639 == last.rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006641 uint32_t id = last.rawPointerData.pointers[0].id;
6642 current.rawPointerData.pointers[0].id = id;
6643 current.rawPointerData.idToIndex[id] = 0;
6644 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006645 return;
6646 }
6647
6648 // General case.
6649 // We build a heap of squared euclidean distances between current and last pointers
6650 // associated with the current and last pointer indices. Then, we find the best
6651 // match (by distance) for each current pointer.
6652 // The pointers must have the same tool type but it is possible for them to
6653 // transition from hovering to touching or vice-versa while retaining the same id.
6654 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6655
6656 uint32_t heapSize = 0;
6657 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6658 currentPointerIndex++) {
6659 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6660 lastPointerIndex++) {
6661 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006662 current.rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006664 last.rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006665 if (currentPointer.toolType == lastPointer.toolType) {
6666 int64_t deltaX = currentPointer.x - lastPointer.x;
6667 int64_t deltaY = currentPointer.y - lastPointer.y;
6668
6669 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6670
6671 // Insert new element into the heap (sift up).
6672 heap[heapSize].currentPointerIndex = currentPointerIndex;
6673 heap[heapSize].lastPointerIndex = lastPointerIndex;
6674 heap[heapSize].distance = distance;
6675 heapSize += 1;
6676 }
6677 }
6678 }
6679
6680 // Heapify
6681 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6682 startIndex -= 1;
6683 for (uint32_t parentIndex = startIndex; ;) {
6684 uint32_t childIndex = parentIndex * 2 + 1;
6685 if (childIndex >= heapSize) {
6686 break;
6687 }
6688
6689 if (childIndex + 1 < heapSize
6690 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6691 childIndex += 1;
6692 }
6693
6694 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6695 break;
6696 }
6697
6698 swap(heap[parentIndex], heap[childIndex]);
6699 parentIndex = childIndex;
6700 }
6701 }
6702
6703#if DEBUG_POINTER_ASSIGNMENT
6704 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6705 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006706 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006707 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6708 heap[i].distance);
6709 }
6710#endif
6711
6712 // Pull matches out by increasing order of distance.
6713 // To avoid reassigning pointers that have already been matched, the loop keeps track
6714 // of which last and current pointers have been matched using the matchedXXXBits variables.
6715 // It also tracks the used pointer id bits.
6716 BitSet32 matchedLastBits(0);
6717 BitSet32 matchedCurrentBits(0);
6718 BitSet32 usedIdBits(0);
6719 bool first = true;
6720 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6721 while (heapSize > 0) {
6722 if (first) {
6723 // The first time through the loop, we just consume the root element of
6724 // the heap (the one with smallest distance).
6725 first = false;
6726 } else {
6727 // Previous iterations consumed the root element of the heap.
6728 // Pop root element off of the heap (sift down).
6729 heap[0] = heap[heapSize];
6730 for (uint32_t parentIndex = 0; ;) {
6731 uint32_t childIndex = parentIndex * 2 + 1;
6732 if (childIndex >= heapSize) {
6733 break;
6734 }
6735
6736 if (childIndex + 1 < heapSize
6737 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6738 childIndex += 1;
6739 }
6740
6741 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6742 break;
6743 }
6744
6745 swap(heap[parentIndex], heap[childIndex]);
6746 parentIndex = childIndex;
6747 }
6748
6749#if DEBUG_POINTER_ASSIGNMENT
6750 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6751 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006752 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006753 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6754 heap[i].distance);
6755 }
6756#endif
6757 }
6758
6759 heapSize -= 1;
6760
6761 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6762 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6763
6764 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6765 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6766
6767 matchedCurrentBits.markBit(currentPointerIndex);
6768 matchedLastBits.markBit(lastPointerIndex);
6769
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006770 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
6771 current.rawPointerData.pointers[currentPointerIndex].id = id;
6772 current.rawPointerData.idToIndex[id] = currentPointerIndex;
6773 current.rawPointerData.markIdBit(id,
6774 current.rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006775 usedIdBits.markBit(id);
6776
6777#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006778 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6779 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006780 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6781#endif
6782 break;
6783 }
6784 }
6785
6786 // Assign fresh ids to pointers that were not matched in the process.
6787 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6788 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6789 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6790
Siarhei Vishniakouf43b65c2021-06-21 22:30:51 +00006791 current.rawPointerData.pointers[currentPointerIndex].id = id;
6792 current.rawPointerData.idToIndex[id] = currentPointerIndex;
6793 current.rawPointerData.markIdBit(id,
6794 current.rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006795
6796#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006797 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006798#endif
6799 }
6800}
6801
6802int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6803 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6804 return AKEY_STATE_VIRTUAL;
6805 }
6806
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006807 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006808 if (virtualKey.keyCode == keyCode) {
6809 return AKEY_STATE_UP;
6810 }
6811 }
6812
6813 return AKEY_STATE_UNKNOWN;
6814}
6815
6816int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6817 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6818 return AKEY_STATE_VIRTUAL;
6819 }
6820
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006821 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006822 if (virtualKey.scanCode == scanCode) {
6823 return AKEY_STATE_UP;
6824 }
6825 }
6826
6827 return AKEY_STATE_UNKNOWN;
6828}
6829
6830bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6831 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006832 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006833 for (size_t i = 0; i < numCodes; i++) {
6834 if (virtualKey.keyCode == keyCodes[i]) {
6835 outFlags[i] = 1;
6836 }
6837 }
6838 }
6839
6840 return true;
6841}
6842
Arthur Hungc23540e2018-11-29 20:42:11 +08006843std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6844 if (mParameters.hasAssociatedDisplay) {
6845 if (mDeviceMode == DEVICE_MODE_POINTER) {
6846 return std::make_optional(mPointerController->getDisplayId());
6847 } else {
6848 return std::make_optional(mViewport.displayId);
6849 }
6850 }
6851 return std::nullopt;
6852}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006853
6854// --- SingleTouchInputMapper ---
6855
6856SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6857 TouchInputMapper(device) {
6858}
6859
6860SingleTouchInputMapper::~SingleTouchInputMapper() {
6861}
6862
6863void SingleTouchInputMapper::reset(nsecs_t when) {
6864 mSingleTouchMotionAccumulator.reset(getDevice());
6865
6866 TouchInputMapper::reset(when);
6867}
6868
6869void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6870 TouchInputMapper::process(rawEvent);
6871
6872 mSingleTouchMotionAccumulator.process(rawEvent);
6873}
6874
Michael Wright842500e2015-03-13 17:32:02 -07006875void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006876 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006877 outState->rawPointerData.pointerCount = 1;
6878 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006879
6880 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6881 && (mTouchButtonAccumulator.isHovering()
6882 || (mRawPointerAxes.pressure.valid
6883 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006884 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006885
Michael Wright842500e2015-03-13 17:32:02 -07006886 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006887 outPointer.id = 0;
6888 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6889 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6890 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6891 outPointer.touchMajor = 0;
6892 outPointer.touchMinor = 0;
6893 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6894 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6895 outPointer.orientation = 0;
6896 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6897 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6898 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6899 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6900 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6901 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6902 }
6903 outPointer.isHovering = isHovering;
6904 }
6905}
6906
6907void SingleTouchInputMapper::configureRawPointerAxes() {
6908 TouchInputMapper::configureRawPointerAxes();
6909
6910 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6911 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6912 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6913 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6914 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6915 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6916 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6917}
6918
6919bool SingleTouchInputMapper::hasStylus() const {
6920 return mTouchButtonAccumulator.hasStylus();
6921}
6922
6923
6924// --- MultiTouchInputMapper ---
6925
6926MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6927 TouchInputMapper(device) {
6928}
6929
6930MultiTouchInputMapper::~MultiTouchInputMapper() {
6931}
6932
6933void MultiTouchInputMapper::reset(nsecs_t when) {
6934 mMultiTouchMotionAccumulator.reset(getDevice());
6935
6936 mPointerIdBits.clear();
6937
6938 TouchInputMapper::reset(when);
6939}
6940
6941void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6942 TouchInputMapper::process(rawEvent);
6943
6944 mMultiTouchMotionAccumulator.process(rawEvent);
6945}
6946
Michael Wright842500e2015-03-13 17:32:02 -07006947void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006948 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6949 size_t outCount = 0;
6950 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006951 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006952
6953 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6954 const MultiTouchMotionAccumulator::Slot* inSlot =
6955 mMultiTouchMotionAccumulator.getSlot(inIndex);
6956 if (!inSlot->isInUse()) {
6957 continue;
6958 }
6959
6960 if (outCount >= MAX_POINTERS) {
6961#if DEBUG_POINTERS
6962 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6963 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006964 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006965#endif
6966 break; // too many fingers!
6967 }
6968
Michael Wright842500e2015-03-13 17:32:02 -07006969 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006970 outPointer.x = inSlot->getX();
6971 outPointer.y = inSlot->getY();
6972 outPointer.pressure = inSlot->getPressure();
6973 outPointer.touchMajor = inSlot->getTouchMajor();
6974 outPointer.touchMinor = inSlot->getTouchMinor();
6975 outPointer.toolMajor = inSlot->getToolMajor();
6976 outPointer.toolMinor = inSlot->getToolMinor();
6977 outPointer.orientation = inSlot->getOrientation();
6978 outPointer.distance = inSlot->getDistance();
6979 outPointer.tiltX = 0;
6980 outPointer.tiltY = 0;
6981
6982 outPointer.toolType = inSlot->getToolType();
6983 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6984 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6985 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6986 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6987 }
6988 }
6989
6990 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6991 && (mTouchButtonAccumulator.isHovering()
6992 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6993 outPointer.isHovering = isHovering;
6994
6995 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006996 if (mHavePointerIds) {
6997 int32_t trackingId = inSlot->getTrackingId();
6998 int32_t id = -1;
6999 if (trackingId >= 0) {
7000 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7001 uint32_t n = idBits.clearFirstMarkedBit();
7002 if (mPointerTrackingIdMap[n] == trackingId) {
7003 id = n;
7004 }
7005 }
7006
7007 if (id < 0 && !mPointerIdBits.isFull()) {
7008 id = mPointerIdBits.markFirstUnmarkedBit();
7009 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007010 }
Michael Wright842500e2015-03-13 17:32:02 -07007011 }
gaoshang1a632de2016-08-24 10:23:50 +08007012 if (id < 0) {
7013 mHavePointerIds = false;
7014 outState->rawPointerData.clearIdBits();
7015 newPointerIdBits.clear();
7016 } else {
7017 outPointer.id = id;
7018 outState->rawPointerData.idToIndex[id] = outCount;
7019 outState->rawPointerData.markIdBit(id, isHovering);
7020 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007021 }
Michael Wright842500e2015-03-13 17:32:02 -07007022 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007023 outCount += 1;
7024 }
7025
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007026 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007027 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007028 mPointerIdBits = newPointerIdBits;
7029
7030 mMultiTouchMotionAccumulator.finishSync();
7031}
7032
7033void MultiTouchInputMapper::configureRawPointerAxes() {
7034 TouchInputMapper::configureRawPointerAxes();
7035
7036 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7037 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7038 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7039 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7040 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7041 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7042 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7043 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7044 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7045 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7046 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7047
7048 if (mRawPointerAxes.trackingId.valid
7049 && mRawPointerAxes.slot.valid
7050 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7051 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7052 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007053 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7054 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007055 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007056 slotCount = MAX_SLOTS;
7057 }
7058 mMultiTouchMotionAccumulator.configure(getDevice(),
7059 slotCount, true /*usingSlotsProtocol*/);
7060 } else {
7061 mMultiTouchMotionAccumulator.configure(getDevice(),
7062 MAX_POINTERS, false /*usingSlotsProtocol*/);
7063 }
7064}
7065
7066bool MultiTouchInputMapper::hasStylus() const {
7067 return mMultiTouchMotionAccumulator.hasStylus()
7068 || mTouchButtonAccumulator.hasStylus();
7069}
7070
Michael Wright842500e2015-03-13 17:32:02 -07007071// --- ExternalStylusInputMapper
7072
7073ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7074 InputMapper(device) {
7075
7076}
7077
7078uint32_t ExternalStylusInputMapper::getSources() {
7079 return AINPUT_SOURCE_STYLUS;
7080}
7081
7082void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7083 InputMapper::populateDeviceInfo(info);
7084 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7085 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7086}
7087
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007088void ExternalStylusInputMapper::dump(std::string& dump) {
7089 dump += INDENT2 "External Stylus Input Mapper:\n";
7090 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007091 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007092 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007093 dumpStylusState(dump, mStylusState);
7094}
7095
7096void ExternalStylusInputMapper::configure(nsecs_t when,
7097 const InputReaderConfiguration* config, uint32_t changes) {
7098 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7099 mTouchButtonAccumulator.configure(getDevice());
7100}
7101
7102void ExternalStylusInputMapper::reset(nsecs_t when) {
7103 InputDevice* device = getDevice();
7104 mSingleTouchMotionAccumulator.reset(device);
7105 mTouchButtonAccumulator.reset(device);
7106 InputMapper::reset(when);
7107}
7108
7109void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7110 mSingleTouchMotionAccumulator.process(rawEvent);
7111 mTouchButtonAccumulator.process(rawEvent);
7112
7113 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7114 sync(rawEvent->when);
7115 }
7116}
7117
7118void ExternalStylusInputMapper::sync(nsecs_t when) {
7119 mStylusState.clear();
7120
7121 mStylusState.when = when;
7122
Michael Wright45ccacf2015-04-21 19:01:58 +01007123 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7124 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7125 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7126 }
7127
Michael Wright842500e2015-03-13 17:32:02 -07007128 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7129 if (mRawPressureAxis.valid) {
7130 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7131 } else if (mTouchButtonAccumulator.isToolActive()) {
7132 mStylusState.pressure = 1.0f;
7133 } else {
7134 mStylusState.pressure = 0.0f;
7135 }
7136
7137 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007138
7139 mContext->dispatchExternalStylusState(mStylusState);
7140}
7141
Michael Wrightd02c5b62014-02-10 15:10:22 -08007142
7143// --- JoystickInputMapper ---
7144
7145JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7146 InputMapper(device) {
7147}
7148
7149JoystickInputMapper::~JoystickInputMapper() {
7150}
7151
7152uint32_t JoystickInputMapper::getSources() {
7153 return AINPUT_SOURCE_JOYSTICK;
7154}
7155
7156void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7157 InputMapper::populateDeviceInfo(info);
7158
7159 for (size_t i = 0; i < mAxes.size(); i++) {
7160 const Axis& axis = mAxes.valueAt(i);
7161 addMotionRange(axis.axisInfo.axis, axis, info);
7162
7163 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7164 addMotionRange(axis.axisInfo.highAxis, axis, info);
7165
7166 }
7167 }
7168}
7169
7170void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7171 InputDeviceInfo* info) {
7172 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7173 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7174 /* In order to ease the transition for developers from using the old axes
7175 * to the newer, more semantically correct axes, we'll continue to register
7176 * the old axes as duplicates of their corresponding new ones. */
7177 int32_t compatAxis = getCompatAxis(axisId);
7178 if (compatAxis >= 0) {
7179 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7180 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7181 }
7182}
7183
7184/* A mapping from axes the joystick actually has to the axes that should be
7185 * artificially created for compatibility purposes.
7186 * Returns -1 if no compatibility axis is needed. */
7187int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7188 switch(axis) {
7189 case AMOTION_EVENT_AXIS_LTRIGGER:
7190 return AMOTION_EVENT_AXIS_BRAKE;
7191 case AMOTION_EVENT_AXIS_RTRIGGER:
7192 return AMOTION_EVENT_AXIS_GAS;
7193 }
7194 return -1;
7195}
7196
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007197void JoystickInputMapper::dump(std::string& dump) {
7198 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007199
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007200 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007201 size_t numAxes = mAxes.size();
7202 for (size_t i = 0; i < numAxes; i++) {
7203 const Axis& axis = mAxes.valueAt(i);
7204 const char* label = getAxisLabel(axis.axisInfo.axis);
7205 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007206 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007207 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007208 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007209 }
7210 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7211 label = getAxisLabel(axis.axisInfo.highAxis);
7212 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007213 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007214 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007215 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007216 axis.axisInfo.splitValue);
7217 }
7218 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007219 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007220 }
7221
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007222 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 -08007223 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007224 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007225 "highScale=%0.5f, highOffset=%0.5f\n",
7226 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007227 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007228 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7229 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7230 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7231 }
7232}
7233
7234void JoystickInputMapper::configure(nsecs_t when,
7235 const InputReaderConfiguration* config, uint32_t changes) {
7236 InputMapper::configure(when, config, changes);
7237
7238 if (!changes) { // first time only
7239 // Collect all axes.
7240 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7241 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7242 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7243 continue; // axis must be claimed by a different device
7244 }
7245
7246 RawAbsoluteAxisInfo rawAxisInfo;
7247 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7248 if (rawAxisInfo.valid) {
7249 // Map axis.
7250 AxisInfo axisInfo;
7251 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7252 if (!explicitlyMapped) {
7253 // Axis is not explicitly mapped, will choose a generic axis later.
7254 axisInfo.mode = AxisInfo::MODE_NORMAL;
7255 axisInfo.axis = -1;
7256 }
7257
7258 // Apply flat override.
7259 int32_t rawFlat = axisInfo.flatOverride < 0
7260 ? rawAxisInfo.flat : axisInfo.flatOverride;
7261
7262 // Calculate scaling factors and limits.
7263 Axis axis;
7264 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7265 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7266 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7267 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7268 scale, 0.0f, highScale, 0.0f,
7269 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7270 rawAxisInfo.resolution * scale);
7271 } else if (isCenteredAxis(axisInfo.axis)) {
7272 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7273 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7274 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7275 scale, offset, scale, offset,
7276 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7277 rawAxisInfo.resolution * scale);
7278 } else {
7279 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7280 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7281 scale, 0.0f, scale, 0.0f,
7282 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7283 rawAxisInfo.resolution * scale);
7284 }
7285
7286 // To eliminate noise while the joystick is at rest, filter out small variations
7287 // in axis values up front.
7288 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7289
7290 mAxes.add(abs, axis);
7291 }
7292 }
7293
7294 // If there are too many axes, start dropping them.
7295 // Prefer to keep explicitly mapped axes.
7296 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007297 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007298 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007299 pruneAxes(true);
7300 pruneAxes(false);
7301 }
7302
7303 // Assign generic axis ids to remaining axes.
7304 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7305 size_t numAxes = mAxes.size();
7306 for (size_t i = 0; i < numAxes; i++) {
7307 Axis& axis = mAxes.editValueAt(i);
7308 if (axis.axisInfo.axis < 0) {
7309 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7310 && haveAxis(nextGenericAxisId)) {
7311 nextGenericAxisId += 1;
7312 }
7313
7314 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7315 axis.axisInfo.axis = nextGenericAxisId;
7316 nextGenericAxisId += 1;
7317 } else {
7318 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7319 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007320 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007321 mAxes.removeItemsAt(i--);
7322 numAxes -= 1;
7323 }
7324 }
7325 }
7326 }
7327}
7328
7329bool JoystickInputMapper::haveAxis(int32_t axisId) {
7330 size_t numAxes = mAxes.size();
7331 for (size_t i = 0; i < numAxes; i++) {
7332 const Axis& axis = mAxes.valueAt(i);
7333 if (axis.axisInfo.axis == axisId
7334 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7335 && axis.axisInfo.highAxis == axisId)) {
7336 return true;
7337 }
7338 }
7339 return false;
7340}
7341
7342void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7343 size_t i = mAxes.size();
7344 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7345 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7346 continue;
7347 }
7348 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007349 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007350 mAxes.removeItemsAt(i);
7351 }
7352}
7353
7354bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7355 switch (axis) {
7356 case AMOTION_EVENT_AXIS_X:
7357 case AMOTION_EVENT_AXIS_Y:
7358 case AMOTION_EVENT_AXIS_Z:
7359 case AMOTION_EVENT_AXIS_RX:
7360 case AMOTION_EVENT_AXIS_RY:
7361 case AMOTION_EVENT_AXIS_RZ:
7362 case AMOTION_EVENT_AXIS_HAT_X:
7363 case AMOTION_EVENT_AXIS_HAT_Y:
7364 case AMOTION_EVENT_AXIS_ORIENTATION:
7365 case AMOTION_EVENT_AXIS_RUDDER:
7366 case AMOTION_EVENT_AXIS_WHEEL:
7367 return true;
7368 default:
7369 return false;
7370 }
7371}
7372
7373void JoystickInputMapper::reset(nsecs_t when) {
7374 // Recenter all axes.
7375 size_t numAxes = mAxes.size();
7376 for (size_t i = 0; i < numAxes; i++) {
7377 Axis& axis = mAxes.editValueAt(i);
7378 axis.resetValue();
7379 }
7380
7381 InputMapper::reset(when);
7382}
7383
7384void JoystickInputMapper::process(const RawEvent* rawEvent) {
7385 switch (rawEvent->type) {
7386 case EV_ABS: {
7387 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7388 if (index >= 0) {
7389 Axis& axis = mAxes.editValueAt(index);
7390 float newValue, highNewValue;
7391 switch (axis.axisInfo.mode) {
7392 case AxisInfo::MODE_INVERT:
7393 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7394 * axis.scale + axis.offset;
7395 highNewValue = 0.0f;
7396 break;
7397 case AxisInfo::MODE_SPLIT:
7398 if (rawEvent->value < axis.axisInfo.splitValue) {
7399 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7400 * axis.scale + axis.offset;
7401 highNewValue = 0.0f;
7402 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7403 newValue = 0.0f;
7404 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7405 * axis.highScale + axis.highOffset;
7406 } else {
7407 newValue = 0.0f;
7408 highNewValue = 0.0f;
7409 }
7410 break;
7411 default:
7412 newValue = rawEvent->value * axis.scale + axis.offset;
7413 highNewValue = 0.0f;
7414 break;
7415 }
7416 axis.newValue = newValue;
7417 axis.highNewValue = highNewValue;
7418 }
7419 break;
7420 }
7421
7422 case EV_SYN:
7423 switch (rawEvent->code) {
7424 case SYN_REPORT:
7425 sync(rawEvent->when, false /*force*/);
7426 break;
7427 }
7428 break;
7429 }
7430}
7431
7432void JoystickInputMapper::sync(nsecs_t when, bool force) {
7433 if (!filterAxes(force)) {
7434 return;
7435 }
7436
7437 int32_t metaState = mContext->getGlobalMetaState();
7438 int32_t buttonState = 0;
7439
7440 PointerProperties pointerProperties;
7441 pointerProperties.clear();
7442 pointerProperties.id = 0;
7443 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7444
7445 PointerCoords pointerCoords;
7446 pointerCoords.clear();
7447
7448 size_t numAxes = mAxes.size();
7449 for (size_t i = 0; i < numAxes; i++) {
7450 const Axis& axis = mAxes.valueAt(i);
7451 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7452 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7453 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7454 axis.highCurrentValue);
7455 }
7456 }
7457
7458 // Moving a joystick axis should not wake the device because joysticks can
7459 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7460 // button will likely wake the device.
7461 // TODO: Use the input device configuration to control this behavior more finely.
7462 uint32_t policyFlags = 0;
7463
Prabir Pradhan42611e02018-11-27 14:04:02 -08007464 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7465 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007466 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7467 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7468 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007469 getListener()->notifyMotion(&args);
7470}
7471
7472void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7473 int32_t axis, float value) {
7474 pointerCoords->setAxisValue(axis, value);
7475 /* In order to ease the transition for developers from using the old axes
7476 * to the newer, more semantically correct axes, we'll continue to produce
7477 * values for the old axes as mirrors of the value of their corresponding
7478 * new axes. */
7479 int32_t compatAxis = getCompatAxis(axis);
7480 if (compatAxis >= 0) {
7481 pointerCoords->setAxisValue(compatAxis, value);
7482 }
7483}
7484
7485bool JoystickInputMapper::filterAxes(bool force) {
7486 bool atLeastOneSignificantChange = force;
7487 size_t numAxes = mAxes.size();
7488 for (size_t i = 0; i < numAxes; i++) {
7489 Axis& axis = mAxes.editValueAt(i);
7490 if (force || hasValueChangedSignificantly(axis.filter,
7491 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7492 axis.currentValue = axis.newValue;
7493 atLeastOneSignificantChange = true;
7494 }
7495 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7496 if (force || hasValueChangedSignificantly(axis.filter,
7497 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7498 axis.highCurrentValue = axis.highNewValue;
7499 atLeastOneSignificantChange = true;
7500 }
7501 }
7502 }
7503 return atLeastOneSignificantChange;
7504}
7505
7506bool JoystickInputMapper::hasValueChangedSignificantly(
7507 float filter, float newValue, float currentValue, float min, float max) {
7508 if (newValue != currentValue) {
7509 // Filter out small changes in value unless the value is converging on the axis
7510 // bounds or center point. This is intended to reduce the amount of information
7511 // sent to applications by particularly noisy joysticks (such as PS3).
7512 if (fabs(newValue - currentValue) > filter
7513 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7514 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7515 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7516 return true;
7517 }
7518 }
7519 return false;
7520}
7521
7522bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7523 float filter, float newValue, float currentValue, float thresholdValue) {
7524 float newDistance = fabs(newValue - thresholdValue);
7525 if (newDistance < filter) {
7526 float oldDistance = fabs(currentValue - thresholdValue);
7527 if (newDistance < oldDistance) {
7528 return true;
7529 }
7530 }
7531 return false;
7532}
7533
7534} // namespace android