blob: eee49d5e2a433b17ffbdf8f6689bbf616ba8f978 [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) {
Siarhei Vishniakouc5ae0dc2019-07-10 15:51:18 -0700562 ALOGI("Reconfiguring input devices, changes=%s",
563 InputReaderConfiguration::changesToString(changes).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800564 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
565
566 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
567 mEventHub->requestReopenDevices();
568 } else {
569 for (size_t i = 0; i < mDevices.size(); i++) {
570 InputDevice* device = mDevices.valueAt(i);
571 device->configure(now, &mConfig, changes);
572 }
573 }
574 }
575}
576
577void InputReader::updateGlobalMetaStateLocked() {
578 mGlobalMetaState = 0;
579
580 for (size_t i = 0; i < mDevices.size(); i++) {
581 InputDevice* device = mDevices.valueAt(i);
582 mGlobalMetaState |= device->getMetaState();
583 }
584}
585
586int32_t InputReader::getGlobalMetaStateLocked() {
587 return mGlobalMetaState;
588}
589
Michael Wright842500e2015-03-13 17:32:02 -0700590void InputReader::notifyExternalStylusPresenceChanged() {
591 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
592}
593
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800594void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700595 for (size_t i = 0; i < mDevices.size(); i++) {
596 InputDevice* device = mDevices.valueAt(i);
597 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800598 InputDeviceInfo info;
599 device->getDeviceInfo(&info);
600 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700601 }
602 }
603}
604
605void InputReader::dispatchExternalStylusState(const StylusState& state) {
606 for (size_t i = 0; i < mDevices.size(); i++) {
607 InputDevice* device = mDevices.valueAt(i);
608 device->updateExternalStylusState(state);
609 }
610}
611
Michael Wrightd02c5b62014-02-10 15:10:22 -0800612void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
613 mDisableVirtualKeysTimeout = time;
614}
615
616bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
617 InputDevice* device, int32_t keyCode, int32_t scanCode) {
618 if (now < mDisableVirtualKeysTimeout) {
619 ALOGI("Dropping virtual key from device %s because virtual keys are "
620 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100621 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800622 (mDisableVirtualKeysTimeout - now) * 0.000001,
623 keyCode, scanCode);
624 return true;
625 } else {
626 return false;
627 }
628}
629
630void InputReader::fadePointerLocked() {
631 for (size_t i = 0; i < mDevices.size(); i++) {
632 InputDevice* device = mDevices.valueAt(i);
633 device->fadePointer();
634 }
635}
636
637void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
638 if (when < mNextTimeout) {
639 mNextTimeout = when;
640 mEventHub->wake();
641 }
642}
643
644int32_t InputReader::bumpGenerationLocked() {
645 return ++mGeneration;
646}
647
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800648void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800649 AutoMutex _l(mLock);
650 getInputDevicesLocked(outInputDevices);
651}
652
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800653void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 outInputDevices.clear();
655
656 size_t numDevices = mDevices.size();
657 for (size_t i = 0; i < numDevices; i++) {
658 InputDevice* device = mDevices.valueAt(i);
659 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800660 InputDeviceInfo info;
661 device->getDeviceInfo(&info);
662 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800663 }
664 }
665}
666
667int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
668 int32_t keyCode) {
669 AutoMutex _l(mLock);
670
671 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
672}
673
674int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
675 int32_t scanCode) {
676 AutoMutex _l(mLock);
677
678 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
679}
680
681int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
682 AutoMutex _l(mLock);
683
684 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
685}
686
687int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
688 GetStateFunc getStateFunc) {
689 int32_t result = AKEY_STATE_UNKNOWN;
690 if (deviceId >= 0) {
691 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
692 if (deviceIndex >= 0) {
693 InputDevice* device = mDevices.valueAt(deviceIndex);
694 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
695 result = (device->*getStateFunc)(sourceMask, code);
696 }
697 }
698 } else {
699 size_t numDevices = mDevices.size();
700 for (size_t i = 0; i < numDevices; i++) {
701 InputDevice* device = mDevices.valueAt(i);
702 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
703 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
704 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
705 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
706 if (currentResult >= AKEY_STATE_DOWN) {
707 return currentResult;
708 } else if (currentResult == AKEY_STATE_UP) {
709 result = currentResult;
710 }
711 }
712 }
713 }
714 return result;
715}
716
Andrii Kulian763a3a42016-03-08 10:46:16 -0800717void InputReader::toggleCapsLockState(int32_t deviceId) {
718 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
719 if (deviceIndex < 0) {
720 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
721 return;
722 }
723
724 InputDevice* device = mDevices.valueAt(deviceIndex);
725 if (device->isIgnored()) {
726 return;
727 }
728
729 device->updateMetaState(AKEYCODE_CAPS_LOCK);
730}
731
Michael Wrightd02c5b62014-02-10 15:10:22 -0800732bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
733 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
734 AutoMutex _l(mLock);
735
736 memset(outFlags, 0, numCodes);
737 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
738}
739
740bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
741 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
742 bool result = false;
743 if (deviceId >= 0) {
744 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
745 if (deviceIndex >= 0) {
746 InputDevice* device = mDevices.valueAt(deviceIndex);
747 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
748 result = device->markSupportedKeyCodes(sourceMask,
749 numCodes, keyCodes, outFlags);
750 }
751 }
752 } else {
753 size_t numDevices = mDevices.size();
754 for (size_t i = 0; i < numDevices; i++) {
755 InputDevice* device = mDevices.valueAt(i);
756 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
757 result |= device->markSupportedKeyCodes(sourceMask,
758 numCodes, keyCodes, outFlags);
759 }
760 }
761 }
762 return result;
763}
764
765void InputReader::requestRefreshConfiguration(uint32_t changes) {
766 AutoMutex _l(mLock);
767
768 if (changes) {
769 bool needWake = !mConfigurationChangesToRefresh;
770 mConfigurationChangesToRefresh |= changes;
771
772 if (needWake) {
773 mEventHub->wake();
774 }
775 }
776}
777
778void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
779 ssize_t repeat, int32_t token) {
780 AutoMutex _l(mLock);
781
782 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
783 if (deviceIndex >= 0) {
784 InputDevice* device = mDevices.valueAt(deviceIndex);
785 device->vibrate(pattern, patternSize, repeat, token);
786 }
787}
788
789void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
790 AutoMutex _l(mLock);
791
792 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
793 if (deviceIndex >= 0) {
794 InputDevice* device = mDevices.valueAt(deviceIndex);
795 device->cancelVibrate(token);
796 }
797}
798
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700799bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
800 AutoMutex _l(mLock);
801
802 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
803 if (deviceIndex >= 0) {
804 InputDevice* device = mDevices.valueAt(deviceIndex);
805 return device->isEnabled();
806 }
807 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
808 return false;
809}
810
Arthur Hungc23540e2018-11-29 20:42:11 +0800811bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
812 AutoMutex _l(mLock);
813
814 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
815 if (deviceIndex < 0) {
816 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
817 return false;
818 }
819
820 InputDevice* device = mDevices.valueAt(deviceIndex);
821 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
822 // No associated display. By default, can dispatch to all displays.
823 if (!associatedDisplayId) {
824 return true;
825 }
826
827 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
828 ALOGW("Device has associated, but no associated display id.");
829 return true;
830 }
831
832 return *associatedDisplayId == displayId;
833}
834
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800835void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 AutoMutex _l(mLock);
837
838 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800839 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800841 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800842
843 for (size_t i = 0; i < mDevices.size(); i++) {
844 mDevices.valueAt(i)->dump(dump);
845 }
846
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800847 dump += INDENT "Configuration:\n";
848 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
850 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800851 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100853 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800855 dump += "]\n";
856 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 mConfig.virtualKeyQuietTime * 0.000001f);
858
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800859 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
861 mConfig.pointerVelocityControlParameters.scale,
862 mConfig.pointerVelocityControlParameters.lowThreshold,
863 mConfig.pointerVelocityControlParameters.highThreshold,
864 mConfig.pointerVelocityControlParameters.acceleration);
865
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800866 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
868 mConfig.wheelVelocityControlParameters.scale,
869 mConfig.wheelVelocityControlParameters.lowThreshold,
870 mConfig.wheelVelocityControlParameters.highThreshold,
871 mConfig.wheelVelocityControlParameters.acceleration);
872
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800873 dump += StringPrintf(INDENT2 "PointerGesture:\n");
874 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800875 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800876 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800877 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800878 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800879 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800880 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800881 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800882 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800883 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800884 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800885 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800886 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800887 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800888 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800889 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800890 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800891 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800892 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800893 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800894 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800895 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800896 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800897 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700898
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800899 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700900 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800901}
902
903void InputReader::monitor() {
904 // Acquire and release the lock to ensure that the reader has not deadlocked.
905 mLock.lock();
906 mEventHub->wake();
907 mReaderIsAliveCondition.wait(mLock);
908 mLock.unlock();
909
910 // Check the EventHub
911 mEventHub->monitor();
912}
913
914
915// --- InputReader::ContextImpl ---
916
917InputReader::ContextImpl::ContextImpl(InputReader* reader) :
918 mReader(reader) {
919}
920
921void InputReader::ContextImpl::updateGlobalMetaState() {
922 // lock is already held by the input loop
923 mReader->updateGlobalMetaStateLocked();
924}
925
926int32_t InputReader::ContextImpl::getGlobalMetaState() {
927 // lock is already held by the input loop
928 return mReader->getGlobalMetaStateLocked();
929}
930
931void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
932 // lock is already held by the input loop
933 mReader->disableVirtualKeysUntilLocked(time);
934}
935
936bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
937 InputDevice* device, int32_t keyCode, int32_t scanCode) {
938 // lock is already held by the input loop
939 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
940}
941
942void InputReader::ContextImpl::fadePointer() {
943 // lock is already held by the input loop
944 mReader->fadePointerLocked();
945}
946
947void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
948 // lock is already held by the input loop
949 mReader->requestTimeoutAtTimeLocked(when);
950}
951
952int32_t InputReader::ContextImpl::bumpGeneration() {
953 // lock is already held by the input loop
954 return mReader->bumpGenerationLocked();
955}
956
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800957void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700958 // lock is already held by whatever called refreshConfigurationLocked
959 mReader->getExternalStylusDevicesLocked(outDevices);
960}
961
962void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
963 mReader->dispatchExternalStylusState(state);
964}
965
Michael Wrightd02c5b62014-02-10 15:10:22 -0800966InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
967 return mReader->mPolicy.get();
968}
969
970InputListenerInterface* InputReader::ContextImpl::getListener() {
971 return mReader->mQueuedListener.get();
972}
973
974EventHubInterface* InputReader::ContextImpl::getEventHub() {
975 return mReader->mEventHub.get();
976}
977
Prabir Pradhan42611e02018-11-27 14:04:02 -0800978uint32_t InputReader::ContextImpl::getNextSequenceNum() {
979 return (mReader->mNextSequenceNum)++;
980}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981
Michael Wrightd02c5b62014-02-10 15:10:22 -0800982// --- InputDevice ---
983
984InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
985 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
986 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
987 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700988 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989}
990
991InputDevice::~InputDevice() {
992 size_t numMappers = mMappers.size();
993 for (size_t i = 0; i < numMappers; i++) {
994 delete mMappers[i];
995 }
996 mMappers.clear();
997}
998
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700999bool InputDevice::isEnabled() {
1000 return getEventHub()->isDeviceEnabled(mId);
1001}
1002
1003void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1004 if (isEnabled() == enabled) {
1005 return;
1006 }
1007
1008 if (enabled) {
1009 getEventHub()->enableDevice(mId);
1010 reset(when);
1011 } else {
1012 reset(when);
1013 getEventHub()->disableDevice(mId);
1014 }
1015 // Must change generation to flag this device as changed
1016 bumpGeneration();
1017}
1018
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001021 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001022
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001024 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001025 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1026 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001027 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1028 if (mAssociatedDisplayPort) {
1029 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1030 } else {
1031 dump += "<none>\n";
1032 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001033 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1034 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1035 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001036
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001037 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1038 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001039 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001040 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001041 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001042 const char* label = getAxisLabel(range.axis);
1043 char name[32];
1044 if (label) {
1045 strncpy(name, label, sizeof(name));
1046 name[sizeof(name) - 1] = '\0';
1047 } else {
1048 snprintf(name, sizeof(name), "%d", range.axis);
1049 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001050 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1052 name, range.source, range.min, range.max, range.flat, range.fuzz,
1053 range.resolution);
1054 }
1055 }
1056
1057 size_t numMappers = mMappers.size();
1058 for (size_t i = 0; i < numMappers; i++) {
1059 InputMapper* mapper = mMappers[i];
1060 mapper->dump(dump);
1061 }
1062}
1063
1064void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001065 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001066}
1067
1068void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1069 mSources = 0;
1070
1071 if (!isIgnored()) {
1072 if (!changes) { // first time only
1073 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1074 }
1075
1076 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1077 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1078 sp<KeyCharacterMap> keyboardLayout =
1079 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1080 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1081 bumpGeneration();
1082 }
1083 }
1084 }
1085
1086 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1087 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001088 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 if (mAlias != alias) {
1090 mAlias = alias;
1091 bumpGeneration();
1092 }
1093 }
1094 }
1095
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001096 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1097 ssize_t index = config->disabledDevices.indexOf(mId);
1098 bool enabled = index < 0;
1099 setEnabled(enabled, when);
1100 }
1101
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001102 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1103 // In most situations, no port will be specified.
1104 mAssociatedDisplayPort = std::nullopt;
1105 // Find the display port that corresponds to the current input port.
1106 const std::string& inputPort = mIdentifier.location;
1107 if (!inputPort.empty()) {
1108 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1109 const auto& displayPort = ports.find(inputPort);
1110 if (displayPort != ports.end()) {
1111 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1112 }
1113 }
1114 }
1115
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001116 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 mapper->configure(when, config, changes);
1118 mSources |= mapper->getSources();
1119 }
1120 }
1121}
1122
1123void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001124 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001125 mapper->reset(when);
1126 }
1127
1128 mContext->updateGlobalMetaState();
1129
1130 notifyReset(when);
1131}
1132
1133void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1134 // Process all of the events in order for each mapper.
1135 // We cannot simply ask each mapper to process them in bulk because mappers may
1136 // have side-effects that must be interleaved. For example, joystick movement events and
1137 // gamepad button presses are handled by different mappers but they should be dispatched
1138 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001139 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001141 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1143 rawEvent->when);
1144#endif
1145
1146 if (mDropUntilNextSync) {
1147 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1148 mDropUntilNextSync = false;
1149#if DEBUG_RAW_EVENTS
1150 ALOGD("Recovered from input event buffer overrun.");
1151#endif
1152 } else {
1153#if DEBUG_RAW_EVENTS
1154 ALOGD("Dropped input event while waiting for next input sync.");
1155#endif
1156 }
1157 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001158 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159 mDropUntilNextSync = true;
1160 reset(rawEvent->when);
1161 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001162 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001163 mapper->process(rawEvent);
1164 }
1165 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001166 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001167 }
1168}
1169
1170void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001171 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 mapper->timeoutExpired(when);
1173 }
1174}
1175
Michael Wright842500e2015-03-13 17:32:02 -07001176void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001177 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001178 mapper->updateExternalStylusState(state);
1179 }
1180}
1181
Michael Wrightd02c5b62014-02-10 15:10:22 -08001182void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1183 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001184 mIsExternal, mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001185 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001186 mapper->populateDeviceInfo(outDeviceInfo);
1187 }
1188}
1189
1190int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1191 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1192}
1193
1194int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1195 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1196}
1197
1198int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1199 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1200}
1201
1202int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1203 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001204 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001205 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1206 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1207 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1208 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1209 if (currentResult >= AKEY_STATE_DOWN) {
1210 return currentResult;
1211 } else if (currentResult == AKEY_STATE_UP) {
1212 result = currentResult;
1213 }
1214 }
1215 }
1216 return result;
1217}
1218
1219bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1220 const int32_t* keyCodes, uint8_t* outFlags) {
1221 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001222 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001223 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1224 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1225 }
1226 }
1227 return result;
1228}
1229
1230void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1231 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001232 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001233 mapper->vibrate(pattern, patternSize, repeat, token);
1234 }
1235}
1236
1237void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001238 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239 mapper->cancelVibrate(token);
1240 }
1241}
1242
Jeff Brownc9aa6282015-02-11 19:03:28 -08001243void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001244 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001245 mapper->cancelTouch(when);
1246 }
1247}
1248
Michael Wrightd02c5b62014-02-10 15:10:22 -08001249int32_t InputDevice::getMetaState() {
1250 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001251 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001252 result |= mapper->getMetaState();
1253 }
1254 return result;
1255}
1256
Andrii Kulian763a3a42016-03-08 10:46:16 -08001257void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001258 for (InputMapper* mapper : mMappers) {
1259 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001260 }
1261}
1262
Michael Wrightd02c5b62014-02-10 15:10:22 -08001263void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001264 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001265 mapper->fadePointer();
1266 }
1267}
1268
1269void InputDevice::bumpGeneration() {
1270 mGeneration = mContext->bumpGeneration();
1271}
1272
1273void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001274 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 mContext->getListener()->notifyDeviceReset(&args);
1276}
1277
Arthur Hungc23540e2018-11-29 20:42:11 +08001278std::optional<int32_t> InputDevice::getAssociatedDisplay() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001279 for (InputMapper* mapper : mMappers) {
Arthur Hungc23540e2018-11-29 20:42:11 +08001280 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1281 if (associatedDisplayId) {
1282 return associatedDisplayId;
1283 }
1284 }
1285
1286 return std::nullopt;
1287}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288
1289// --- CursorButtonAccumulator ---
1290
1291CursorButtonAccumulator::CursorButtonAccumulator() {
1292 clearButtons();
1293}
1294
1295void CursorButtonAccumulator::reset(InputDevice* device) {
1296 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1297 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1298 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1299 mBtnBack = device->isKeyPressed(BTN_BACK);
1300 mBtnSide = device->isKeyPressed(BTN_SIDE);
1301 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1302 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1303 mBtnTask = device->isKeyPressed(BTN_TASK);
1304}
1305
1306void CursorButtonAccumulator::clearButtons() {
1307 mBtnLeft = 0;
1308 mBtnRight = 0;
1309 mBtnMiddle = 0;
1310 mBtnBack = 0;
1311 mBtnSide = 0;
1312 mBtnForward = 0;
1313 mBtnExtra = 0;
1314 mBtnTask = 0;
1315}
1316
1317void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1318 if (rawEvent->type == EV_KEY) {
1319 switch (rawEvent->code) {
1320 case BTN_LEFT:
1321 mBtnLeft = rawEvent->value;
1322 break;
1323 case BTN_RIGHT:
1324 mBtnRight = rawEvent->value;
1325 break;
1326 case BTN_MIDDLE:
1327 mBtnMiddle = rawEvent->value;
1328 break;
1329 case BTN_BACK:
1330 mBtnBack = rawEvent->value;
1331 break;
1332 case BTN_SIDE:
1333 mBtnSide = rawEvent->value;
1334 break;
1335 case BTN_FORWARD:
1336 mBtnForward = rawEvent->value;
1337 break;
1338 case BTN_EXTRA:
1339 mBtnExtra = rawEvent->value;
1340 break;
1341 case BTN_TASK:
1342 mBtnTask = rawEvent->value;
1343 break;
1344 }
1345 }
1346}
1347
1348uint32_t CursorButtonAccumulator::getButtonState() const {
1349 uint32_t result = 0;
1350 if (mBtnLeft) {
1351 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1352 }
1353 if (mBtnRight) {
1354 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1355 }
1356 if (mBtnMiddle) {
1357 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1358 }
1359 if (mBtnBack || mBtnSide) {
1360 result |= AMOTION_EVENT_BUTTON_BACK;
1361 }
1362 if (mBtnForward || mBtnExtra) {
1363 result |= AMOTION_EVENT_BUTTON_FORWARD;
1364 }
1365 return result;
1366}
1367
1368
1369// --- CursorMotionAccumulator ---
1370
1371CursorMotionAccumulator::CursorMotionAccumulator() {
1372 clearRelativeAxes();
1373}
1374
1375void CursorMotionAccumulator::reset(InputDevice* device) {
1376 clearRelativeAxes();
1377}
1378
1379void CursorMotionAccumulator::clearRelativeAxes() {
1380 mRelX = 0;
1381 mRelY = 0;
1382}
1383
1384void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1385 if (rawEvent->type == EV_REL) {
1386 switch (rawEvent->code) {
1387 case REL_X:
1388 mRelX = rawEvent->value;
1389 break;
1390 case REL_Y:
1391 mRelY = rawEvent->value;
1392 break;
1393 }
1394 }
1395}
1396
1397void CursorMotionAccumulator::finishSync() {
1398 clearRelativeAxes();
1399}
1400
1401
1402// --- CursorScrollAccumulator ---
1403
1404CursorScrollAccumulator::CursorScrollAccumulator() :
1405 mHaveRelWheel(false), mHaveRelHWheel(false) {
1406 clearRelativeAxes();
1407}
1408
1409void CursorScrollAccumulator::configure(InputDevice* device) {
1410 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1411 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1412}
1413
1414void CursorScrollAccumulator::reset(InputDevice* device) {
1415 clearRelativeAxes();
1416}
1417
1418void CursorScrollAccumulator::clearRelativeAxes() {
1419 mRelWheel = 0;
1420 mRelHWheel = 0;
1421}
1422
1423void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1424 if (rawEvent->type == EV_REL) {
1425 switch (rawEvent->code) {
1426 case REL_WHEEL:
1427 mRelWheel = rawEvent->value;
1428 break;
1429 case REL_HWHEEL:
1430 mRelHWheel = rawEvent->value;
1431 break;
1432 }
1433 }
1434}
1435
1436void CursorScrollAccumulator::finishSync() {
1437 clearRelativeAxes();
1438}
1439
1440
1441// --- TouchButtonAccumulator ---
1442
1443TouchButtonAccumulator::TouchButtonAccumulator() :
1444 mHaveBtnTouch(false), mHaveStylus(false) {
1445 clearButtons();
1446}
1447
1448void TouchButtonAccumulator::configure(InputDevice* device) {
1449 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1450 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1451 || device->hasKey(BTN_TOOL_RUBBER)
1452 || device->hasKey(BTN_TOOL_BRUSH)
1453 || device->hasKey(BTN_TOOL_PENCIL)
1454 || device->hasKey(BTN_TOOL_AIRBRUSH);
1455}
1456
1457void TouchButtonAccumulator::reset(InputDevice* device) {
1458 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1459 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001460 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1461 mBtnStylus2 =
1462 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001463 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1464 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1465 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1466 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1467 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1468 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1469 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1470 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1471 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1472 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1473 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1474}
1475
1476void TouchButtonAccumulator::clearButtons() {
1477 mBtnTouch = 0;
1478 mBtnStylus = 0;
1479 mBtnStylus2 = 0;
1480 mBtnToolFinger = 0;
1481 mBtnToolPen = 0;
1482 mBtnToolRubber = 0;
1483 mBtnToolBrush = 0;
1484 mBtnToolPencil = 0;
1485 mBtnToolAirbrush = 0;
1486 mBtnToolMouse = 0;
1487 mBtnToolLens = 0;
1488 mBtnToolDoubleTap = 0;
1489 mBtnToolTripleTap = 0;
1490 mBtnToolQuadTap = 0;
1491}
1492
1493void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1494 if (rawEvent->type == EV_KEY) {
1495 switch (rawEvent->code) {
1496 case BTN_TOUCH:
1497 mBtnTouch = rawEvent->value;
1498 break;
1499 case BTN_STYLUS:
1500 mBtnStylus = rawEvent->value;
1501 break;
1502 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001503 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001504 mBtnStylus2 = rawEvent->value;
1505 break;
1506 case BTN_TOOL_FINGER:
1507 mBtnToolFinger = rawEvent->value;
1508 break;
1509 case BTN_TOOL_PEN:
1510 mBtnToolPen = rawEvent->value;
1511 break;
1512 case BTN_TOOL_RUBBER:
1513 mBtnToolRubber = rawEvent->value;
1514 break;
1515 case BTN_TOOL_BRUSH:
1516 mBtnToolBrush = rawEvent->value;
1517 break;
1518 case BTN_TOOL_PENCIL:
1519 mBtnToolPencil = rawEvent->value;
1520 break;
1521 case BTN_TOOL_AIRBRUSH:
1522 mBtnToolAirbrush = rawEvent->value;
1523 break;
1524 case BTN_TOOL_MOUSE:
1525 mBtnToolMouse = rawEvent->value;
1526 break;
1527 case BTN_TOOL_LENS:
1528 mBtnToolLens = rawEvent->value;
1529 break;
1530 case BTN_TOOL_DOUBLETAP:
1531 mBtnToolDoubleTap = rawEvent->value;
1532 break;
1533 case BTN_TOOL_TRIPLETAP:
1534 mBtnToolTripleTap = rawEvent->value;
1535 break;
1536 case BTN_TOOL_QUADTAP:
1537 mBtnToolQuadTap = rawEvent->value;
1538 break;
1539 }
1540 }
1541}
1542
1543uint32_t TouchButtonAccumulator::getButtonState() const {
1544 uint32_t result = 0;
1545 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001546 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001547 }
1548 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001549 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001550 }
1551 return result;
1552}
1553
1554int32_t TouchButtonAccumulator::getToolType() const {
1555 if (mBtnToolMouse || mBtnToolLens) {
1556 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1557 }
1558 if (mBtnToolRubber) {
1559 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1560 }
1561 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1562 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1563 }
1564 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1565 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1566 }
1567 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1568}
1569
1570bool TouchButtonAccumulator::isToolActive() const {
1571 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1572 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1573 || mBtnToolMouse || mBtnToolLens
1574 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1575}
1576
1577bool TouchButtonAccumulator::isHovering() const {
1578 return mHaveBtnTouch && !mBtnTouch;
1579}
1580
1581bool TouchButtonAccumulator::hasStylus() const {
1582 return mHaveStylus;
1583}
1584
1585
1586// --- RawPointerAxes ---
1587
1588RawPointerAxes::RawPointerAxes() {
1589 clear();
1590}
1591
1592void RawPointerAxes::clear() {
1593 x.clear();
1594 y.clear();
1595 pressure.clear();
1596 touchMajor.clear();
1597 touchMinor.clear();
1598 toolMajor.clear();
1599 toolMinor.clear();
1600 orientation.clear();
1601 distance.clear();
1602 tiltX.clear();
1603 tiltY.clear();
1604 trackingId.clear();
1605 slot.clear();
1606}
1607
1608
1609// --- RawPointerData ---
1610
1611RawPointerData::RawPointerData() {
1612 clear();
1613}
1614
1615void RawPointerData::clear() {
1616 pointerCount = 0;
1617 clearIdBits();
1618}
1619
1620void RawPointerData::copyFrom(const RawPointerData& other) {
1621 pointerCount = other.pointerCount;
1622 hoveringIdBits = other.hoveringIdBits;
1623 touchingIdBits = other.touchingIdBits;
1624
1625 for (uint32_t i = 0; i < pointerCount; i++) {
1626 pointers[i] = other.pointers[i];
1627
1628 int id = pointers[i].id;
1629 idToIndex[id] = other.idToIndex[id];
1630 }
1631}
1632
1633void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1634 float x = 0, y = 0;
1635 uint32_t count = touchingIdBits.count();
1636 if (count) {
1637 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1638 uint32_t id = idBits.clearFirstMarkedBit();
1639 const Pointer& pointer = pointerForId(id);
1640 x += pointer.x;
1641 y += pointer.y;
1642 }
1643 x /= count;
1644 y /= count;
1645 }
1646 *outX = x;
1647 *outY = y;
1648}
1649
1650
1651// --- CookedPointerData ---
1652
1653CookedPointerData::CookedPointerData() {
1654 clear();
1655}
1656
1657void CookedPointerData::clear() {
1658 pointerCount = 0;
1659 hoveringIdBits.clear();
1660 touchingIdBits.clear();
1661}
1662
1663void CookedPointerData::copyFrom(const CookedPointerData& other) {
1664 pointerCount = other.pointerCount;
1665 hoveringIdBits = other.hoveringIdBits;
1666 touchingIdBits = other.touchingIdBits;
1667
1668 for (uint32_t i = 0; i < pointerCount; i++) {
1669 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1670 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1671
1672 int id = pointerProperties[i].id;
1673 idToIndex[id] = other.idToIndex[id];
1674 }
1675}
1676
1677
1678// --- SingleTouchMotionAccumulator ---
1679
1680SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1681 clearAbsoluteAxes();
1682}
1683
1684void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1685 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1686 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1687 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1688 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1689 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1690 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1691 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1692}
1693
1694void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1695 mAbsX = 0;
1696 mAbsY = 0;
1697 mAbsPressure = 0;
1698 mAbsToolWidth = 0;
1699 mAbsDistance = 0;
1700 mAbsTiltX = 0;
1701 mAbsTiltY = 0;
1702}
1703
1704void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1705 if (rawEvent->type == EV_ABS) {
1706 switch (rawEvent->code) {
1707 case ABS_X:
1708 mAbsX = rawEvent->value;
1709 break;
1710 case ABS_Y:
1711 mAbsY = rawEvent->value;
1712 break;
1713 case ABS_PRESSURE:
1714 mAbsPressure = rawEvent->value;
1715 break;
1716 case ABS_TOOL_WIDTH:
1717 mAbsToolWidth = rawEvent->value;
1718 break;
1719 case ABS_DISTANCE:
1720 mAbsDistance = rawEvent->value;
1721 break;
1722 case ABS_TILT_X:
1723 mAbsTiltX = rawEvent->value;
1724 break;
1725 case ABS_TILT_Y:
1726 mAbsTiltY = rawEvent->value;
1727 break;
1728 }
1729 }
1730}
1731
1732
1733// --- MultiTouchMotionAccumulator ---
1734
Atif Niyaz21da0ff2019-06-28 13:22:51 -07001735MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1736 : mCurrentSlot(-1),
1737 mSlots(nullptr),
1738 mSlotCount(0),
1739 mUsingSlotsProtocol(false),
1740 mHaveStylus(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001741
1742MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1743 delete[] mSlots;
1744}
1745
1746void MultiTouchMotionAccumulator::configure(InputDevice* device,
1747 size_t slotCount, bool usingSlotsProtocol) {
1748 mSlotCount = slotCount;
1749 mUsingSlotsProtocol = usingSlotsProtocol;
1750 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1751
1752 delete[] mSlots;
1753 mSlots = new Slot[slotCount];
1754}
1755
1756void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1757 // Unfortunately there is no way to read the initial contents of the slots.
1758 // So when we reset the accumulator, we must assume they are all zeroes.
1759 if (mUsingSlotsProtocol) {
1760 // Query the driver for the current slot index and use it as the initial slot
1761 // before we start reading events from the device. It is possible that the
1762 // current slot index will not be the same as it was when the first event was
1763 // written into the evdev buffer, which means the input mapper could start
1764 // out of sync with the initial state of the events in the evdev buffer.
1765 // In the extremely unlikely case that this happens, the data from
1766 // two slots will be confused until the next ABS_MT_SLOT event is received.
1767 // This can cause the touch point to "jump", but at least there will be
1768 // no stuck touches.
1769 int32_t initialSlot;
1770 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1771 ABS_MT_SLOT, &initialSlot);
1772 if (status) {
1773 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1774 initialSlot = -1;
1775 }
1776 clearSlots(initialSlot);
1777 } else {
1778 clearSlots(-1);
1779 }
1780}
1781
1782void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1783 if (mSlots) {
1784 for (size_t i = 0; i < mSlotCount; i++) {
1785 mSlots[i].clear();
1786 }
1787 }
1788 mCurrentSlot = initialSlot;
1789}
1790
1791void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1792 if (rawEvent->type == EV_ABS) {
1793 bool newSlot = false;
1794 if (mUsingSlotsProtocol) {
1795 if (rawEvent->code == ABS_MT_SLOT) {
1796 mCurrentSlot = rawEvent->value;
1797 newSlot = true;
1798 }
1799 } else if (mCurrentSlot < 0) {
1800 mCurrentSlot = 0;
1801 }
1802
1803 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1804#if DEBUG_POINTERS
1805 if (newSlot) {
1806 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001807 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001808 mCurrentSlot, mSlotCount - 1);
1809 }
1810#endif
1811 } else {
1812 Slot* slot = &mSlots[mCurrentSlot];
1813
1814 switch (rawEvent->code) {
1815 case ABS_MT_POSITION_X:
1816 slot->mInUse = true;
1817 slot->mAbsMTPositionX = rawEvent->value;
1818 break;
1819 case ABS_MT_POSITION_Y:
1820 slot->mInUse = true;
1821 slot->mAbsMTPositionY = rawEvent->value;
1822 break;
1823 case ABS_MT_TOUCH_MAJOR:
1824 slot->mInUse = true;
1825 slot->mAbsMTTouchMajor = rawEvent->value;
1826 break;
1827 case ABS_MT_TOUCH_MINOR:
1828 slot->mInUse = true;
1829 slot->mAbsMTTouchMinor = rawEvent->value;
1830 slot->mHaveAbsMTTouchMinor = true;
1831 break;
1832 case ABS_MT_WIDTH_MAJOR:
1833 slot->mInUse = true;
1834 slot->mAbsMTWidthMajor = rawEvent->value;
1835 break;
1836 case ABS_MT_WIDTH_MINOR:
1837 slot->mInUse = true;
1838 slot->mAbsMTWidthMinor = rawEvent->value;
1839 slot->mHaveAbsMTWidthMinor = true;
1840 break;
1841 case ABS_MT_ORIENTATION:
1842 slot->mInUse = true;
1843 slot->mAbsMTOrientation = rawEvent->value;
1844 break;
1845 case ABS_MT_TRACKING_ID:
1846 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1847 // The slot is no longer in use but it retains its previous contents,
1848 // which may be reused for subsequent touches.
1849 slot->mInUse = false;
1850 } else {
1851 slot->mInUse = true;
1852 slot->mAbsMTTrackingId = rawEvent->value;
1853 }
1854 break;
1855 case ABS_MT_PRESSURE:
1856 slot->mInUse = true;
1857 slot->mAbsMTPressure = rawEvent->value;
1858 break;
1859 case ABS_MT_DISTANCE:
1860 slot->mInUse = true;
1861 slot->mAbsMTDistance = rawEvent->value;
1862 break;
1863 case ABS_MT_TOOL_TYPE:
1864 slot->mInUse = true;
1865 slot->mAbsMTToolType = rawEvent->value;
1866 slot->mHaveAbsMTToolType = true;
1867 break;
1868 }
1869 }
1870 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1871 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1872 mCurrentSlot += 1;
1873 }
1874}
1875
1876void MultiTouchMotionAccumulator::finishSync() {
1877 if (!mUsingSlotsProtocol) {
1878 clearSlots(-1);
1879 }
1880}
1881
1882bool MultiTouchMotionAccumulator::hasStylus() const {
1883 return mHaveStylus;
1884}
1885
1886
1887// --- MultiTouchMotionAccumulator::Slot ---
1888
1889MultiTouchMotionAccumulator::Slot::Slot() {
1890 clear();
1891}
1892
1893void MultiTouchMotionAccumulator::Slot::clear() {
1894 mInUse = false;
1895 mHaveAbsMTTouchMinor = false;
1896 mHaveAbsMTWidthMinor = false;
1897 mHaveAbsMTToolType = false;
1898 mAbsMTPositionX = 0;
1899 mAbsMTPositionY = 0;
1900 mAbsMTTouchMajor = 0;
1901 mAbsMTTouchMinor = 0;
1902 mAbsMTWidthMajor = 0;
1903 mAbsMTWidthMinor = 0;
1904 mAbsMTOrientation = 0;
1905 mAbsMTTrackingId = -1;
1906 mAbsMTPressure = 0;
1907 mAbsMTDistance = 0;
1908 mAbsMTToolType = 0;
1909}
1910
1911int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1912 if (mHaveAbsMTToolType) {
1913 switch (mAbsMTToolType) {
1914 case MT_TOOL_FINGER:
1915 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1916 case MT_TOOL_PEN:
1917 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1918 }
1919 }
1920 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1921}
1922
1923
1924// --- InputMapper ---
1925
1926InputMapper::InputMapper(InputDevice* device) :
1927 mDevice(device), mContext(device->getContext()) {
1928}
1929
1930InputMapper::~InputMapper() {
1931}
1932
1933void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1934 info->addSource(getSources());
1935}
1936
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001937void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001938}
1939
1940void InputMapper::configure(nsecs_t when,
1941 const InputReaderConfiguration* config, uint32_t changes) {
1942}
1943
1944void InputMapper::reset(nsecs_t when) {
1945}
1946
1947void InputMapper::timeoutExpired(nsecs_t when) {
1948}
1949
1950int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1951 return AKEY_STATE_UNKNOWN;
1952}
1953
1954int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1955 return AKEY_STATE_UNKNOWN;
1956}
1957
1958int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1959 return AKEY_STATE_UNKNOWN;
1960}
1961
1962bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1963 const int32_t* keyCodes, uint8_t* outFlags) {
1964 return false;
1965}
1966
1967void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1968 int32_t token) {
1969}
1970
1971void InputMapper::cancelVibrate(int32_t token) {
1972}
1973
Jeff Brownc9aa6282015-02-11 19:03:28 -08001974void InputMapper::cancelTouch(nsecs_t when) {
1975}
1976
Michael Wrightd02c5b62014-02-10 15:10:22 -08001977int32_t InputMapper::getMetaState() {
1978 return 0;
1979}
1980
Andrii Kulian763a3a42016-03-08 10:46:16 -08001981void InputMapper::updateMetaState(int32_t keyCode) {
1982}
1983
Michael Wright842500e2015-03-13 17:32:02 -07001984void InputMapper::updateExternalStylusState(const StylusState& state) {
1985
1986}
1987
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988void InputMapper::fadePointer() {
1989}
1990
1991status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1992 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1993}
1994
1995void InputMapper::bumpGeneration() {
1996 mDevice->bumpGeneration();
1997}
1998
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001999void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000 const RawAbsoluteAxisInfo& axis, const char* name) {
2001 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002002 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2004 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002005 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006 }
2007}
2008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002009void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2010 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2011 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2012 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2013 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002014}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015
2016// --- SwitchInputMapper ---
2017
2018SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002019 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020}
2021
2022SwitchInputMapper::~SwitchInputMapper() {
2023}
2024
2025uint32_t SwitchInputMapper::getSources() {
2026 return AINPUT_SOURCE_SWITCH;
2027}
2028
2029void SwitchInputMapper::process(const RawEvent* rawEvent) {
2030 switch (rawEvent->type) {
2031 case EV_SW:
2032 processSwitch(rawEvent->code, rawEvent->value);
2033 break;
2034
2035 case EV_SYN:
2036 if (rawEvent->code == SYN_REPORT) {
2037 sync(rawEvent->when);
2038 }
2039 }
2040}
2041
2042void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2043 if (switchCode >= 0 && switchCode < 32) {
2044 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002045 mSwitchValues |= 1 << switchCode;
2046 } else {
2047 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 }
2049 mUpdatedSwitchMask |= 1 << switchCode;
2050 }
2051}
2052
2053void SwitchInputMapper::sync(nsecs_t when) {
2054 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002055 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002056 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2057 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002058 getListener()->notifySwitch(&args);
2059
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060 mUpdatedSwitchMask = 0;
2061 }
2062}
2063
2064int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2065 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2066}
2067
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002068void SwitchInputMapper::dump(std::string& dump) {
2069 dump += INDENT2 "Switch Input Mapper:\n";
2070 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002071}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072
2073// --- VibratorInputMapper ---
2074
2075VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2076 InputMapper(device), mVibrating(false) {
2077}
2078
2079VibratorInputMapper::~VibratorInputMapper() {
2080}
2081
2082uint32_t VibratorInputMapper::getSources() {
2083 return 0;
2084}
2085
2086void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2087 InputMapper::populateDeviceInfo(info);
2088
2089 info->setVibrator(true);
2090}
2091
2092void VibratorInputMapper::process(const RawEvent* rawEvent) {
2093 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2094}
2095
2096void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2097 int32_t token) {
2098#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002099 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002100 for (size_t i = 0; i < patternSize; i++) {
2101 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002102 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002103 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002104 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002106 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002107 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108#endif
2109
2110 mVibrating = true;
2111 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2112 mPatternSize = patternSize;
2113 mRepeat = repeat;
2114 mToken = token;
2115 mIndex = -1;
2116
2117 nextStep();
2118}
2119
2120void VibratorInputMapper::cancelVibrate(int32_t token) {
2121#if DEBUG_VIBRATOR
2122 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2123#endif
2124
2125 if (mVibrating && mToken == token) {
2126 stopVibrating();
2127 }
2128}
2129
2130void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2131 if (mVibrating) {
2132 if (when >= mNextStepTime) {
2133 nextStep();
2134 } else {
2135 getContext()->requestTimeoutAtTime(mNextStepTime);
2136 }
2137 }
2138}
2139
2140void VibratorInputMapper::nextStep() {
2141 mIndex += 1;
2142 if (size_t(mIndex) >= mPatternSize) {
2143 if (mRepeat < 0) {
2144 // We are done.
2145 stopVibrating();
2146 return;
2147 }
2148 mIndex = mRepeat;
2149 }
2150
2151 bool vibratorOn = mIndex & 1;
2152 nsecs_t duration = mPattern[mIndex];
2153 if (vibratorOn) {
2154#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002155 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002156#endif
2157 getEventHub()->vibrate(getDeviceId(), duration);
2158 } else {
2159#if DEBUG_VIBRATOR
2160 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2161#endif
2162 getEventHub()->cancelVibrate(getDeviceId());
2163 }
2164 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2165 mNextStepTime = now + duration;
2166 getContext()->requestTimeoutAtTime(mNextStepTime);
2167#if DEBUG_VIBRATOR
2168 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2169#endif
2170}
2171
2172void VibratorInputMapper::stopVibrating() {
2173 mVibrating = false;
2174#if DEBUG_VIBRATOR
2175 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2176#endif
2177 getEventHub()->cancelVibrate(getDeviceId());
2178}
2179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002180void VibratorInputMapper::dump(std::string& dump) {
2181 dump += INDENT2 "Vibrator Input Mapper:\n";
2182 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183}
2184
2185
2186// --- KeyboardInputMapper ---
2187
2188KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2189 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002190 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002191}
2192
2193KeyboardInputMapper::~KeyboardInputMapper() {
2194}
2195
2196uint32_t KeyboardInputMapper::getSources() {
2197 return mSource;
2198}
2199
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002200int32_t KeyboardInputMapper::getOrientation() {
2201 if (mViewport) {
2202 return mViewport->orientation;
2203 }
2204 return DISPLAY_ORIENTATION_0;
2205}
2206
2207int32_t KeyboardInputMapper::getDisplayId() {
2208 if (mViewport) {
2209 return mViewport->displayId;
2210 }
2211 return ADISPLAY_ID_NONE;
2212}
2213
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2215 InputMapper::populateDeviceInfo(info);
2216
2217 info->setKeyboardType(mKeyboardType);
2218 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2219}
2220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002221void KeyboardInputMapper::dump(std::string& dump) {
2222 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002224 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002225 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002226 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2227 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2228 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229}
2230
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231void KeyboardInputMapper::configure(nsecs_t when,
2232 const InputReaderConfiguration* config, uint32_t changes) {
2233 InputMapper::configure(when, config, changes);
2234
2235 if (!changes) { // first time only
2236 // Configure basic parameters.
2237 configureParameters();
2238 }
2239
2240 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002241 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002242 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243 }
2244 }
2245}
2246
Ivan Podogovb9afef32017-02-13 15:34:32 +00002247static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2248 int32_t mapped = 0;
2249 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2250 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2251 if (stemKeyRotationMap[i][0] == keyCode) {
2252 stemKeyRotationMap[i][1] = mapped;
2253 return;
2254 }
2255 }
2256 }
2257}
2258
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259void KeyboardInputMapper::configureParameters() {
2260 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002261 const PropertyMap& config = getDevice()->getConfiguration();
2262 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263 mParameters.orientationAware);
2264
Michael Wrightd02c5b62014-02-10 15:10:22 -08002265 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002266 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2267 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2268 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2269 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002271
2272 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002273 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002274 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275}
2276
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002277void KeyboardInputMapper::dumpParameters(std::string& dump) {
2278 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002279 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002281 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002282 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002283}
2284
2285void KeyboardInputMapper::reset(nsecs_t when) {
2286 mMetaState = AMETA_NONE;
2287 mDownTime = 0;
2288 mKeyDowns.clear();
2289 mCurrentHidUsage = 0;
2290
2291 resetLedState();
2292
2293 InputMapper::reset(when);
2294}
2295
2296void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2297 switch (rawEvent->type) {
2298 case EV_KEY: {
2299 int32_t scanCode = rawEvent->code;
2300 int32_t usageCode = mCurrentHidUsage;
2301 mCurrentHidUsage = 0;
2302
2303 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002304 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002305 }
2306 break;
2307 }
2308 case EV_MSC: {
2309 if (rawEvent->code == MSC_SCAN) {
2310 mCurrentHidUsage = rawEvent->value;
2311 }
2312 break;
2313 }
2314 case EV_SYN: {
2315 if (rawEvent->code == SYN_REPORT) {
2316 mCurrentHidUsage = 0;
2317 }
2318 }
2319 }
2320}
2321
2322bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2323 return scanCode < BTN_MOUSE
2324 || scanCode >= KEY_OK
2325 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2326 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2327}
2328
Michael Wright58ba9882017-07-26 16:19:11 +01002329bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2330 switch (keyCode) {
2331 case AKEYCODE_MEDIA_PLAY:
2332 case AKEYCODE_MEDIA_PAUSE:
2333 case AKEYCODE_MEDIA_PLAY_PAUSE:
2334 case AKEYCODE_MUTE:
2335 case AKEYCODE_HEADSETHOOK:
2336 case AKEYCODE_MEDIA_STOP:
2337 case AKEYCODE_MEDIA_NEXT:
2338 case AKEYCODE_MEDIA_PREVIOUS:
2339 case AKEYCODE_MEDIA_REWIND:
2340 case AKEYCODE_MEDIA_RECORD:
2341 case AKEYCODE_MEDIA_FAST_FORWARD:
2342 case AKEYCODE_MEDIA_SKIP_FORWARD:
2343 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2344 case AKEYCODE_MEDIA_STEP_FORWARD:
2345 case AKEYCODE_MEDIA_STEP_BACKWARD:
2346 case AKEYCODE_MEDIA_AUDIO_TRACK:
2347 case AKEYCODE_VOLUME_UP:
2348 case AKEYCODE_VOLUME_DOWN:
2349 case AKEYCODE_VOLUME_MUTE:
2350 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2351 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2352 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2353 return true;
2354 }
2355 return false;
2356}
2357
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002358void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2359 int32_t usageCode) {
2360 int32_t keyCode;
2361 int32_t keyMetaState;
2362 uint32_t policyFlags;
2363
2364 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2365 &keyCode, &keyMetaState, &policyFlags)) {
2366 keyCode = AKEYCODE_UNKNOWN;
2367 keyMetaState = mMetaState;
2368 policyFlags = 0;
2369 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002370
2371 if (down) {
2372 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002373 if (mParameters.orientationAware) {
2374 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375 }
2376
2377 // Add key down.
2378 ssize_t keyDownIndex = findKeyDown(scanCode);
2379 if (keyDownIndex >= 0) {
2380 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002381 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002382 } else {
2383 // key down
2384 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2385 && mContext->shouldDropVirtualKey(when,
2386 getDevice(), keyCode, scanCode)) {
2387 return;
2388 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002389 if (policyFlags & POLICY_FLAG_GESTURE) {
2390 mDevice->cancelTouch(when);
2391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002392
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002393 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002394 keyDown.keyCode = keyCode;
2395 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002396 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 }
2398
2399 mDownTime = when;
2400 } else {
2401 // Remove key down.
2402 ssize_t keyDownIndex = findKeyDown(scanCode);
2403 if (keyDownIndex >= 0) {
2404 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002405 keyCode = mKeyDowns[keyDownIndex].keyCode;
2406 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407 } else {
2408 // key was not actually down
2409 ALOGI("Dropping key up from device %s because the key was not down. "
2410 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002411 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 return;
2413 }
2414 }
2415
Andrii Kulian763a3a42016-03-08 10:46:16 -08002416 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002417 // If global meta state changed send it along with the key.
2418 // If it has not changed then we'll use what keymap gave us,
2419 // since key replacement logic might temporarily reset a few
2420 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002421 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 }
2423
2424 nsecs_t downTime = mDownTime;
2425
2426 // Key down on external an keyboard should wake the device.
2427 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2428 // For internal keyboards, the key layout file should specify the policy flags for
2429 // each wake key individually.
2430 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002431 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002432 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 }
2434
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002435 if (mParameters.handlesKeyRepeat) {
2436 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2437 }
2438
Prabir Pradhan42611e02018-11-27 14:04:02 -08002439 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2440 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002441 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002442 getListener()->notifyKey(&args);
2443}
2444
2445ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2446 size_t n = mKeyDowns.size();
2447 for (size_t i = 0; i < n; i++) {
2448 if (mKeyDowns[i].scanCode == scanCode) {
2449 return i;
2450 }
2451 }
2452 return -1;
2453}
2454
2455int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2456 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2457}
2458
2459int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2460 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2461}
2462
2463bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2464 const int32_t* keyCodes, uint8_t* outFlags) {
2465 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2466}
2467
2468int32_t KeyboardInputMapper::getMetaState() {
2469 return mMetaState;
2470}
2471
Andrii Kulian763a3a42016-03-08 10:46:16 -08002472void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2473 updateMetaStateIfNeeded(keyCode, false);
2474}
2475
2476bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2477 int32_t oldMetaState = mMetaState;
2478 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2479 bool metaStateChanged = oldMetaState != newMetaState;
2480 if (metaStateChanged) {
2481 mMetaState = newMetaState;
2482 updateLedState(false);
2483
2484 getContext()->updateGlobalMetaState();
2485 }
2486
2487 return metaStateChanged;
2488}
2489
Michael Wrightd02c5b62014-02-10 15:10:22 -08002490void KeyboardInputMapper::resetLedState() {
2491 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2492 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2493 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2494
2495 updateLedState(true);
2496}
2497
2498void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2499 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2500 ledState.on = false;
2501}
2502
2503void KeyboardInputMapper::updateLedState(bool reset) {
2504 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2505 AMETA_CAPS_LOCK_ON, reset);
2506 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2507 AMETA_NUM_LOCK_ON, reset);
2508 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2509 AMETA_SCROLL_LOCK_ON, reset);
2510}
2511
2512void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2513 int32_t led, int32_t modifier, bool reset) {
2514 if (ledState.avail) {
2515 bool desiredState = (mMetaState & modifier) != 0;
2516 if (reset || ledState.on != desiredState) {
2517 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2518 ledState.on = desiredState;
2519 }
2520 }
2521}
2522
2523
2524// --- CursorInputMapper ---
2525
2526CursorInputMapper::CursorInputMapper(InputDevice* device) :
2527 InputMapper(device) {
2528}
2529
2530CursorInputMapper::~CursorInputMapper() {
2531}
2532
2533uint32_t CursorInputMapper::getSources() {
2534 return mSource;
2535}
2536
2537void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2538 InputMapper::populateDeviceInfo(info);
2539
2540 if (mParameters.mode == Parameters::MODE_POINTER) {
2541 float minX, minY, maxX, maxY;
2542 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2543 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2544 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2545 }
2546 } else {
2547 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2548 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2549 }
2550 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2551
2552 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2553 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2554 }
2555 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2556 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2557 }
2558}
2559
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002560void CursorInputMapper::dump(std::string& dump) {
2561 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002562 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002563 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2564 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2565 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2566 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2567 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002569 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002570 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002571 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2572 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2573 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2574 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2575 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2576 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577}
2578
2579void CursorInputMapper::configure(nsecs_t when,
2580 const InputReaderConfiguration* config, uint32_t changes) {
2581 InputMapper::configure(when, config, changes);
2582
2583 if (!changes) { // first time only
2584 mCursorScrollAccumulator.configure(getDevice());
2585
2586 // Configure basic parameters.
2587 configureParameters();
2588
2589 // Configure device mode.
2590 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002591 case Parameters::MODE_POINTER_RELATIVE:
2592 // Should not happen during first time configuration.
2593 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2594 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002595 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 case Parameters::MODE_POINTER:
2597 mSource = AINPUT_SOURCE_MOUSE;
2598 mXPrecision = 1.0f;
2599 mYPrecision = 1.0f;
2600 mXScale = 1.0f;
2601 mYScale = 1.0f;
2602 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2603 break;
2604 case Parameters::MODE_NAVIGATION:
2605 mSource = AINPUT_SOURCE_TRACKBALL;
2606 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2607 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2608 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2609 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2610 break;
2611 }
2612
2613 mVWheelScale = 1.0f;
2614 mHWheelScale = 1.0f;
2615 }
2616
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002617 if ((!changes && config->pointerCapture)
2618 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2619 if (config->pointerCapture) {
2620 if (mParameters.mode == Parameters::MODE_POINTER) {
2621 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2622 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2623 // Keep PointerController around in order to preserve the pointer position.
2624 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2625 } else {
2626 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2627 }
2628 } else {
2629 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2630 mParameters.mode = Parameters::MODE_POINTER;
2631 mSource = AINPUT_SOURCE_MOUSE;
2632 } else {
2633 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2634 }
2635 }
2636 bumpGeneration();
2637 if (changes) {
2638 getDevice()->notifyReset(when);
2639 }
2640 }
2641
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2643 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2644 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2645 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2646 }
2647
2648 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002649 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002650 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002651 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002652 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002653 if (internalViewport) {
2654 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002656 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002657
2658 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002659 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002660 getPolicy()->obtainPointerController(getDeviceId());
2661 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002662 bumpGeneration();
2663 }
2664}
2665
2666void CursorInputMapper::configureParameters() {
2667 mParameters.mode = Parameters::MODE_POINTER;
2668 String8 cursorModeString;
2669 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2670 if (cursorModeString == "navigation") {
2671 mParameters.mode = Parameters::MODE_NAVIGATION;
2672 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2673 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2674 }
2675 }
2676
2677 mParameters.orientationAware = false;
2678 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2679 mParameters.orientationAware);
2680
2681 mParameters.hasAssociatedDisplay = false;
2682 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2683 mParameters.hasAssociatedDisplay = true;
2684 }
2685}
2686
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002687void CursorInputMapper::dumpParameters(std::string& dump) {
2688 dump += INDENT3 "Parameters:\n";
2689 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 toString(mParameters.hasAssociatedDisplay));
2691
2692 switch (mParameters.mode) {
2693 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002694 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002696 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002697 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002698 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002699 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002700 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002701 break;
2702 default:
2703 ALOG_ASSERT(false);
2704 }
2705
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002706 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002707 toString(mParameters.orientationAware));
2708}
2709
2710void CursorInputMapper::reset(nsecs_t when) {
2711 mButtonState = 0;
2712 mDownTime = 0;
2713
2714 mPointerVelocityControl.reset();
2715 mWheelXVelocityControl.reset();
2716 mWheelYVelocityControl.reset();
2717
2718 mCursorButtonAccumulator.reset(getDevice());
2719 mCursorMotionAccumulator.reset(getDevice());
2720 mCursorScrollAccumulator.reset(getDevice());
2721
2722 InputMapper::reset(when);
2723}
2724
2725void CursorInputMapper::process(const RawEvent* rawEvent) {
2726 mCursorButtonAccumulator.process(rawEvent);
2727 mCursorMotionAccumulator.process(rawEvent);
2728 mCursorScrollAccumulator.process(rawEvent);
2729
2730 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2731 sync(rawEvent->when);
2732 }
2733}
2734
2735void CursorInputMapper::sync(nsecs_t when) {
2736 int32_t lastButtonState = mButtonState;
2737 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2738 mButtonState = currentButtonState;
2739
2740 bool wasDown = isPointerDown(lastButtonState);
2741 bool down = isPointerDown(currentButtonState);
2742 bool downChanged;
2743 if (!wasDown && down) {
2744 mDownTime = when;
2745 downChanged = true;
2746 } else if (wasDown && !down) {
2747 downChanged = true;
2748 } else {
2749 downChanged = false;
2750 }
2751 nsecs_t downTime = mDownTime;
2752 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002753 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2754 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002755
2756 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2757 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2758 bool moved = deltaX != 0 || deltaY != 0;
2759
2760 // Rotate delta according to orientation if needed.
2761 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2762 && (deltaX != 0.0f || deltaY != 0.0f)) {
2763 rotateDelta(mOrientation, &deltaX, &deltaY);
2764 }
2765
2766 // Move the pointer.
2767 PointerProperties pointerProperties;
2768 pointerProperties.clear();
2769 pointerProperties.id = 0;
2770 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2771
2772 PointerCoords pointerCoords;
2773 pointerCoords.clear();
2774
2775 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2776 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2777 bool scrolled = vscroll != 0 || hscroll != 0;
2778
Yi Kong9b14ac62018-07-17 13:48:38 -07002779 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2780 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002781
2782 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2783
2784 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002785 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2786 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002787 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002788 if (moved || scrolled || buttonsChanged) {
2789 mPointerController->setPresentation(
2790 PointerControllerInterface::PRESENTATION_POINTER);
2791
2792 if (moved) {
2793 mPointerController->move(deltaX, deltaY);
2794 }
2795
2796 if (buttonsChanged) {
2797 mPointerController->setButtonState(currentButtonState);
2798 }
2799
2800 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2801 }
2802
Garfield Tan00f511d2019-06-12 16:55:40 -07002803 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2804 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2807 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002808 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002809 } else {
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2811 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2812 displayId = ADISPLAY_ID_NONE;
2813 }
2814
2815 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2816
2817 // Moving an external trackball or mouse should wake the device.
2818 // We don't do this for internal cursor devices to prevent them from waking up
2819 // the device in your pocket.
2820 // TODO: Use the input device configuration to control this behavior more finely.
2821 uint32_t policyFlags = 0;
2822 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002823 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 }
2825
2826 // Synthesize key down from buttons if needed.
2827 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002828 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829
2830 // Send motion event.
2831 if (downChanged || moved || scrolled || buttonsChanged) {
2832 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002833 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834 int32_t motionEventAction;
2835 if (downChanged) {
2836 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002837 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2839 } else {
2840 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2841 }
2842
Michael Wright7b159c92015-05-14 14:48:03 +01002843 if (buttonsReleased) {
2844 BitSet32 released(buttonsReleased);
2845 while (!released.isEmpty()) {
2846 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2847 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002848 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002849 mSource, displayId, policyFlags,
2850 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2851 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002852 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002853 &pointerCoords, mXPrecision, mYPrecision,
2854 xCursorPosition, yCursorPosition, downTime,
2855 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002856 getListener()->notifyMotion(&releaseArgs);
2857 }
2858 }
2859
Prabir Pradhan42611e02018-11-27 14:04:02 -08002860 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Garfield Tan00f511d2019-06-12 16:55:40 -07002861 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2862 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002863 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
Garfield Tan00f511d2019-06-12 16:55:40 -07002864 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2865 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866 getListener()->notifyMotion(&args);
2867
Michael Wright7b159c92015-05-14 14:48:03 +01002868 if (buttonsPressed) {
2869 BitSet32 pressed(buttonsPressed);
2870 while (!pressed.isEmpty()) {
2871 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2872 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002873 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002874 mSource, displayId, policyFlags,
2875 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2876 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002877 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002878 &pointerCoords, mXPrecision, mYPrecision,
2879 xCursorPosition, yCursorPosition, downTime,
2880 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002881 getListener()->notifyMotion(&pressArgs);
2882 }
2883 }
2884
2885 ALOG_ASSERT(buttonState == currentButtonState);
2886
Michael Wrightd02c5b62014-02-10 15:10:22 -08002887 // Send hover move after UP to tell the application that the mouse is hovering now.
2888 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002889 && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002890 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2891 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2892 0, metaState, currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002893 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002894 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002895 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 getListener()->notifyMotion(&hoverArgs);
2897 }
2898
2899 // Send scroll events.
2900 if (scrolled) {
2901 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2902 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2903
Prabir Pradhan42611e02018-11-27 14:04:02 -08002904 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002905 mSource, displayId, policyFlags,
2906 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2907 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002908 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002909 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002910 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002911 getListener()->notifyMotion(&scrollArgs);
2912 }
2913 }
2914
2915 // Synthesize key up from buttons if needed.
2916 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002917 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918
2919 mCursorMotionAccumulator.finishSync();
2920 mCursorScrollAccumulator.finishSync();
2921}
2922
2923int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2924 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2925 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2926 } else {
2927 return AKEY_STATE_UNKNOWN;
2928 }
2929}
2930
2931void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002932 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002933 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2934 }
2935}
2936
Arthur Hungc23540e2018-11-29 20:42:11 +08002937std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2938 if (mParameters.hasAssociatedDisplay) {
2939 if (mParameters.mode == Parameters::MODE_POINTER) {
2940 return std::make_optional(mPointerController->getDisplayId());
2941 } else {
2942 // If the device is orientationAware and not a mouse,
2943 // it expects to dispatch events to any display
2944 return std::make_optional(ADISPLAY_ID_NONE);
2945 }
2946 }
2947 return std::nullopt;
2948}
2949
Prashant Malani1941ff52015-08-11 18:29:28 -07002950// --- RotaryEncoderInputMapper ---
2951
2952RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002953 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002954 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2955}
2956
2957RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2958}
2959
2960uint32_t RotaryEncoderInputMapper::getSources() {
2961 return mSource;
2962}
2963
2964void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2965 InputMapper::populateDeviceInfo(info);
2966
2967 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002968 float res = 0.0f;
2969 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2970 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2971 }
2972 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2973 mScalingFactor)) {
2974 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2975 "default to 1.0!\n");
2976 mScalingFactor = 1.0f;
2977 }
2978 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2979 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002980 }
2981}
2982
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002983void RotaryEncoderInputMapper::dump(std::string& dump) {
2984 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2985 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002986 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2987}
2988
2989void RotaryEncoderInputMapper::configure(nsecs_t when,
2990 const InputReaderConfiguration* config, uint32_t changes) {
2991 InputMapper::configure(when, config, changes);
2992 if (!changes) {
2993 mRotaryEncoderScrollAccumulator.configure(getDevice());
2994 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002995 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002996 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002997 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002998 if (internalViewport) {
2999 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003000 } else {
3001 mOrientation = DISPLAY_ORIENTATION_0;
3002 }
3003 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003004}
3005
3006void RotaryEncoderInputMapper::reset(nsecs_t when) {
3007 mRotaryEncoderScrollAccumulator.reset(getDevice());
3008
3009 InputMapper::reset(when);
3010}
3011
3012void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3013 mRotaryEncoderScrollAccumulator.process(rawEvent);
3014
3015 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3016 sync(rawEvent->when);
3017 }
3018}
3019
3020void RotaryEncoderInputMapper::sync(nsecs_t when) {
3021 PointerCoords pointerCoords;
3022 pointerCoords.clear();
3023
3024 PointerProperties pointerProperties;
3025 pointerProperties.clear();
3026 pointerProperties.id = 0;
3027 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3028
3029 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3030 bool scrolled = scroll != 0;
3031
3032 // This is not a pointer, so it's not associated with a display.
3033 int32_t displayId = ADISPLAY_ID_NONE;
3034
3035 // Moving the rotary encoder should wake the device (if specified).
3036 uint32_t policyFlags = 0;
3037 if (scrolled && getDevice()->isExternal()) {
3038 policyFlags |= POLICY_FLAG_WAKE;
3039 }
3040
Ivan Podogovad437252016-09-29 16:29:55 +01003041 if (mOrientation == DISPLAY_ORIENTATION_180) {
3042 scroll = -scroll;
3043 }
3044
Prashant Malani1941ff52015-08-11 18:29:28 -07003045 // Send motion event.
3046 if (scrolled) {
3047 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003048 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003049
Garfield Tan00f511d2019-06-12 16:55:40 -07003050 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3051 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3052 metaState, /* buttonState */ 0, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07003053 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
3054 &pointerCoords, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Garfield Tan00f511d2019-06-12 16:55:40 -07003055 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003056 getListener()->notifyMotion(&scrollArgs);
3057 }
3058
3059 mRotaryEncoderScrollAccumulator.finishSync();
3060}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003061
3062// --- TouchInputMapper ---
3063
3064TouchInputMapper::TouchInputMapper(InputDevice* device) :
3065 InputMapper(device),
3066 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3067 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003068 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003069 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3070}
3071
3072TouchInputMapper::~TouchInputMapper() {
3073}
3074
3075uint32_t TouchInputMapper::getSources() {
3076 return mSource;
3077}
3078
3079void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3080 InputMapper::populateDeviceInfo(info);
3081
3082 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3083 info->addMotionRange(mOrientedRanges.x);
3084 info->addMotionRange(mOrientedRanges.y);
3085 info->addMotionRange(mOrientedRanges.pressure);
3086
3087 if (mOrientedRanges.haveSize) {
3088 info->addMotionRange(mOrientedRanges.size);
3089 }
3090
3091 if (mOrientedRanges.haveTouchSize) {
3092 info->addMotionRange(mOrientedRanges.touchMajor);
3093 info->addMotionRange(mOrientedRanges.touchMinor);
3094 }
3095
3096 if (mOrientedRanges.haveToolSize) {
3097 info->addMotionRange(mOrientedRanges.toolMajor);
3098 info->addMotionRange(mOrientedRanges.toolMinor);
3099 }
3100
3101 if (mOrientedRanges.haveOrientation) {
3102 info->addMotionRange(mOrientedRanges.orientation);
3103 }
3104
3105 if (mOrientedRanges.haveDistance) {
3106 info->addMotionRange(mOrientedRanges.distance);
3107 }
3108
3109 if (mOrientedRanges.haveTilt) {
3110 info->addMotionRange(mOrientedRanges.tilt);
3111 }
3112
3113 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3114 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3115 0.0f);
3116 }
3117 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3118 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3119 0.0f);
3120 }
3121 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3122 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3123 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3124 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3125 x.fuzz, x.resolution);
3126 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3127 y.fuzz, y.resolution);
3128 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3129 x.fuzz, x.resolution);
3130 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3131 y.fuzz, y.resolution);
3132 }
3133 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3134 }
3135}
3136
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003137void TouchInputMapper::dump(std::string& dump) {
3138 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003139 dumpParameters(dump);
3140 dumpVirtualKeys(dump);
3141 dumpRawPointerAxes(dump);
3142 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003143 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 dumpSurface(dump);
3145
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003146 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3147 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3148 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3149 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3150 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3151 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3152 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3153 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3154 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3155 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3156 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3157 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3158 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3159 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3160 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3161 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3162 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003164 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3165 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003166 mLastRawState.rawPointerData.pointerCount);
3167 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3168 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003169 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003170 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3171 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3172 "toolType=%d, isHovering=%s\n", i,
3173 pointer.id, pointer.x, pointer.y, pointer.pressure,
3174 pointer.touchMajor, pointer.touchMinor,
3175 pointer.toolMajor, pointer.toolMinor,
3176 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3177 pointer.toolType, toString(pointer.isHovering));
3178 }
3179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003180 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3181 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003182 mLastCookedState.cookedPointerData.pointerCount);
3183 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3184 const PointerProperties& pointerProperties =
3185 mLastCookedState.cookedPointerData.pointerProperties[i];
3186 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003187 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3189 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3190 "toolType=%d, isHovering=%s\n", i,
3191 pointerProperties.id,
3192 pointerCoords.getX(),
3193 pointerCoords.getY(),
3194 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3195 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3196 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3197 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3198 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3199 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3200 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3201 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3202 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003203 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003204 }
3205
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003206 dump += INDENT3 "Stylus Fusion:\n";
3207 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003208 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003209 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3210 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003211 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003212 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003213 dumpStylusState(dump, mExternalStylusState);
3214
Michael Wrightd02c5b62014-02-10 15:10:22 -08003215 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003216 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3217 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003219 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003221 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003222 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003223 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003224 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003225 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003226 mPointerGestureMaxSwipeWidth);
3227 }
3228}
3229
Santos Cordonfa5cf462017-04-05 10:37:00 -07003230const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3231 switch (deviceMode) {
3232 case DEVICE_MODE_DISABLED:
3233 return "disabled";
3234 case DEVICE_MODE_DIRECT:
3235 return "direct";
3236 case DEVICE_MODE_UNSCALED:
3237 return "unscaled";
3238 case DEVICE_MODE_NAVIGATION:
3239 return "navigation";
3240 case DEVICE_MODE_POINTER:
3241 return "pointer";
3242 }
3243 return "unknown";
3244}
3245
Michael Wrightd02c5b62014-02-10 15:10:22 -08003246void TouchInputMapper::configure(nsecs_t when,
3247 const InputReaderConfiguration* config, uint32_t changes) {
3248 InputMapper::configure(when, config, changes);
3249
3250 mConfig = *config;
3251
3252 if (!changes) { // first time only
3253 // Configure basic parameters.
3254 configureParameters();
3255
3256 // Configure common accumulators.
3257 mCursorScrollAccumulator.configure(getDevice());
3258 mTouchButtonAccumulator.configure(getDevice());
3259
3260 // Configure absolute axis information.
3261 configureRawPointerAxes();
3262
3263 // Prepare input device calibration.
3264 parseCalibration();
3265 resolveCalibration();
3266 }
3267
Michael Wright842500e2015-03-13 17:32:02 -07003268 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003269 // Update location calibration to reflect current settings
3270 updateAffineTransformation();
3271 }
3272
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3274 // Update pointer speed.
3275 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3276 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3277 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3278 }
3279
3280 bool resetNeeded = false;
3281 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3282 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003283 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3284 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285 // Configure device sources, surface dimensions, orientation and
3286 // scaling factors.
3287 configureSurface(when, &resetNeeded);
3288 }
3289
3290 if (changes && resetNeeded) {
3291 // Send reset, unless this is the first time the device has been configured,
3292 // in which case the reader will call reset itself after all mappers are ready.
3293 getDevice()->notifyReset(when);
3294 }
3295}
3296
Michael Wright842500e2015-03-13 17:32:02 -07003297void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003298 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003299 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003300 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003301
3302 if (!mExternalStylusConnected) {
3303 resetExternalStylus();
3304 }
3305}
3306
Michael Wrightd02c5b62014-02-10 15:10:22 -08003307void TouchInputMapper::configureParameters() {
3308 // Use the pointer presentation mode for devices that do not support distinct
3309 // multitouch. The spot-based presentation relies on being able to accurately
3310 // locate two or more fingers on the touch pad.
3311 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003312 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003313
3314 String8 gestureModeString;
3315 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3316 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003317 if (gestureModeString == "single-touch") {
3318 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3319 } else if (gestureModeString == "multi-touch") {
3320 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003321 } else if (gestureModeString != "default") {
3322 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3323 }
3324 }
3325
3326 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3327 // The device is a touch screen.
3328 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3329 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3330 // The device is a pointing device like a track pad.
3331 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3332 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3333 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3334 // The device is a cursor device with a touch pad attached.
3335 // By default don't use the touch pad to move the pointer.
3336 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3337 } else {
3338 // The device is a touch pad of unknown purpose.
3339 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3340 }
3341
3342 mParameters.hasButtonUnderPad=
3343 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3344
3345 String8 deviceTypeString;
3346 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3347 deviceTypeString)) {
3348 if (deviceTypeString == "touchScreen") {
3349 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3350 } else if (deviceTypeString == "touchPad") {
3351 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3352 } else if (deviceTypeString == "touchNavigation") {
3353 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3354 } else if (deviceTypeString == "pointer") {
3355 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3356 } else if (deviceTypeString != "default") {
3357 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3358 }
3359 }
3360
3361 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3362 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3363 mParameters.orientationAware);
3364
3365 mParameters.hasAssociatedDisplay = false;
3366 mParameters.associatedDisplayIsExternal = false;
3367 if (mParameters.orientationAware
3368 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3369 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3370 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003371 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3372 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003373 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003374 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003375 uniqueDisplayId);
3376 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003377 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003379 if (getDevice()->getAssociatedDisplayPort()) {
3380 mParameters.hasAssociatedDisplay = true;
3381 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003382
3383 // Initial downs on external touch devices should wake the device.
3384 // Normally we don't do this for internal touch screens to prevent them from waking
3385 // up in your pocket but you can enable it using the input device configuration.
3386 mParameters.wake = getDevice()->isExternal();
3387 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3388 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389}
3390
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003391void TouchInputMapper::dumpParameters(std::string& dump) {
3392 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003393
3394 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003395 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003396 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003398 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003399 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 break;
3401 default:
3402 assert(false);
3403 }
3404
3405 switch (mParameters.deviceType) {
3406 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003408 break;
3409 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003410 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003411 break;
3412 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003413 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414 break;
3415 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003416 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003417 break;
3418 default:
3419 ALOG_ASSERT(false);
3420 }
3421
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003422 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003423 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003424 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003425 toString(mParameters.associatedDisplayIsExternal),
3426 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003427 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003428 toString(mParameters.orientationAware));
3429}
3430
3431void TouchInputMapper::configureRawPointerAxes() {
3432 mRawPointerAxes.clear();
3433}
3434
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003435void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3436 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003437 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3438 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3439 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3440 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3441 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3444 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3445 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3446 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3447 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3450}
3451
Michael Wright842500e2015-03-13 17:32:02 -07003452bool TouchInputMapper::hasExternalStylus() const {
3453 return mExternalStylusConnected;
3454}
3455
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003456/**
3457 * Determine which DisplayViewport to use.
3458 * 1. If display port is specified, return the matching viewport. If matching viewport not
3459 * found, then return.
3460 * 2. If a device has associated display, get the matching viewport by either unique id or by
3461 * the display type (internal or external).
3462 * 3. Otherwise, use a non-display viewport.
3463 */
3464std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3465 if (mParameters.hasAssociatedDisplay) {
3466 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3467 if (displayPort) {
3468 // Find the viewport that contains the same port
3469 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3470 if (!v) {
3471 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3472 "but the corresponding viewport is not found.",
3473 getDeviceName().c_str(), *displayPort);
3474 }
3475 return v;
3476 }
3477
3478 if (!mParameters.uniqueDisplayId.empty()) {
3479 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3480 }
3481
3482 ViewportType viewportTypeToUse;
3483 if (mParameters.associatedDisplayIsExternal) {
3484 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3485 } else {
3486 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3487 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003488
3489 std::optional<DisplayViewport> viewport =
3490 mConfig.getDisplayViewportByType(viewportTypeToUse);
3491 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3492 ALOGW("Input device %s should be associated with external display, "
3493 "fallback to internal one for the external viewport is not found.",
3494 getDeviceName().c_str());
3495 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3496 }
3497
3498 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003499 }
3500
3501 DisplayViewport newViewport;
3502 // Raw width and height in the natural orientation.
3503 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3504 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3505 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3506 return std::make_optional(newViewport);
3507}
3508
Michael Wrightd02c5b62014-02-10 15:10:22 -08003509void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3510 int32_t oldDeviceMode = mDeviceMode;
3511
Michael Wright842500e2015-03-13 17:32:02 -07003512 resolveExternalStylusPresence();
3513
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514 // Determine device mode.
3515 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3516 && mConfig.pointerGesturesEnabled) {
3517 mSource = AINPUT_SOURCE_MOUSE;
3518 mDeviceMode = DEVICE_MODE_POINTER;
3519 if (hasStylus()) {
3520 mSource |= AINPUT_SOURCE_STYLUS;
3521 }
3522 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3523 && mParameters.hasAssociatedDisplay) {
3524 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3525 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003526 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 mSource |= AINPUT_SOURCE_STYLUS;
3528 }
Michael Wright2f78b682015-06-12 15:25:08 +01003529 if (hasExternalStylus()) {
3530 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3531 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3533 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3534 mDeviceMode = DEVICE_MODE_NAVIGATION;
3535 } else {
3536 mSource = AINPUT_SOURCE_TOUCHPAD;
3537 mDeviceMode = DEVICE_MODE_UNSCALED;
3538 }
3539
3540 // Ensure we have valid X and Y axes.
3541 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003542 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003543 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003544 mDeviceMode = DEVICE_MODE_DISABLED;
3545 return;
3546 }
3547
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003548 // Get associated display dimensions.
3549 std::optional<DisplayViewport> newViewport = findViewport();
3550 if (!newViewport) {
3551 ALOGI("Touch device '%s' could not query the properties of its associated "
3552 "display. The device will be inoperable until the display size "
3553 "becomes available.",
3554 getDeviceName().c_str());
3555 mDeviceMode = DEVICE_MODE_DISABLED;
3556 return;
3557 }
3558
Michael Wrightd02c5b62014-02-10 15:10:22 -08003559 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003560 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3561 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003562
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003563 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003565 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003566
3567 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3568 // Convert rotated viewport to natural surface coordinates.
3569 int32_t naturalLogicalWidth, naturalLogicalHeight;
3570 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3571 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3572 int32_t naturalDeviceWidth, naturalDeviceHeight;
3573 switch (mViewport.orientation) {
3574 case DISPLAY_ORIENTATION_90:
3575 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3576 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3577 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3578 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3579 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3580 naturalPhysicalTop = mViewport.physicalLeft;
3581 naturalDeviceWidth = mViewport.deviceHeight;
3582 naturalDeviceHeight = mViewport.deviceWidth;
3583 break;
3584 case DISPLAY_ORIENTATION_180:
3585 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3586 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3587 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3588 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3589 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3590 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3591 naturalDeviceWidth = mViewport.deviceWidth;
3592 naturalDeviceHeight = mViewport.deviceHeight;
3593 break;
3594 case DISPLAY_ORIENTATION_270:
3595 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3596 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3597 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3598 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3599 naturalPhysicalLeft = mViewport.physicalTop;
3600 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3601 naturalDeviceWidth = mViewport.deviceHeight;
3602 naturalDeviceHeight = mViewport.deviceWidth;
3603 break;
3604 case DISPLAY_ORIENTATION_0:
3605 default:
3606 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3607 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3608 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3609 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3610 naturalPhysicalLeft = mViewport.physicalLeft;
3611 naturalPhysicalTop = mViewport.physicalTop;
3612 naturalDeviceWidth = mViewport.deviceWidth;
3613 naturalDeviceHeight = mViewport.deviceHeight;
3614 break;
3615 }
3616
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003617 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3618 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3619 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3620 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3621 }
3622
Michael Wright358bcc72018-08-21 04:01:07 +01003623 mPhysicalWidth = naturalPhysicalWidth;
3624 mPhysicalHeight = naturalPhysicalHeight;
3625 mPhysicalLeft = naturalPhysicalLeft;
3626 mPhysicalTop = naturalPhysicalTop;
3627
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3629 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3630 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3631 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3632
3633 mSurfaceOrientation = mParameters.orientationAware ?
3634 mViewport.orientation : DISPLAY_ORIENTATION_0;
3635 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003636 mPhysicalWidth = rawWidth;
3637 mPhysicalHeight = rawHeight;
3638 mPhysicalLeft = 0;
3639 mPhysicalTop = 0;
3640
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 mSurfaceWidth = rawWidth;
3642 mSurfaceHeight = rawHeight;
3643 mSurfaceLeft = 0;
3644 mSurfaceTop = 0;
3645 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3646 }
3647 }
3648
3649 // If moving between pointer modes, need to reset some state.
3650 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3651 if (deviceModeChanged) {
3652 mOrientedRanges.clear();
3653 }
3654
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003655 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003656 if (mDeviceMode == DEVICE_MODE_POINTER ||
3657 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003658 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003659 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3660 }
3661 } else {
3662 mPointerController.clear();
3663 }
3664
3665 if (viewportChanged || deviceModeChanged) {
3666 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3667 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003668 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003669 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3670
3671 // Configure X and Y factors.
3672 mXScale = float(mSurfaceWidth) / rawWidth;
3673 mYScale = float(mSurfaceHeight) / rawHeight;
3674 mXTranslate = -mSurfaceLeft;
3675 mYTranslate = -mSurfaceTop;
3676 mXPrecision = 1.0f / mXScale;
3677 mYPrecision = 1.0f / mYScale;
3678
3679 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3680 mOrientedRanges.x.source = mSource;
3681 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3682 mOrientedRanges.y.source = mSource;
3683
3684 configureVirtualKeys();
3685
3686 // Scale factor for terms that are not oriented in a particular axis.
3687 // If the pixels are square then xScale == yScale otherwise we fake it
3688 // by choosing an average.
3689 mGeometricScale = avg(mXScale, mYScale);
3690
3691 // Size of diagonal axis.
3692 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3693
3694 // Size factors.
3695 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3696 if (mRawPointerAxes.touchMajor.valid
3697 && mRawPointerAxes.touchMajor.maxValue != 0) {
3698 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3699 } else if (mRawPointerAxes.toolMajor.valid
3700 && mRawPointerAxes.toolMajor.maxValue != 0) {
3701 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3702 } else {
3703 mSizeScale = 0.0f;
3704 }
3705
3706 mOrientedRanges.haveTouchSize = true;
3707 mOrientedRanges.haveToolSize = true;
3708 mOrientedRanges.haveSize = true;
3709
3710 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3711 mOrientedRanges.touchMajor.source = mSource;
3712 mOrientedRanges.touchMajor.min = 0;
3713 mOrientedRanges.touchMajor.max = diagonalSize;
3714 mOrientedRanges.touchMajor.flat = 0;
3715 mOrientedRanges.touchMajor.fuzz = 0;
3716 mOrientedRanges.touchMajor.resolution = 0;
3717
3718 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3719 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3720
3721 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3722 mOrientedRanges.toolMajor.source = mSource;
3723 mOrientedRanges.toolMajor.min = 0;
3724 mOrientedRanges.toolMajor.max = diagonalSize;
3725 mOrientedRanges.toolMajor.flat = 0;
3726 mOrientedRanges.toolMajor.fuzz = 0;
3727 mOrientedRanges.toolMajor.resolution = 0;
3728
3729 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3730 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3731
3732 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3733 mOrientedRanges.size.source = mSource;
3734 mOrientedRanges.size.min = 0;
3735 mOrientedRanges.size.max = 1.0;
3736 mOrientedRanges.size.flat = 0;
3737 mOrientedRanges.size.fuzz = 0;
3738 mOrientedRanges.size.resolution = 0;
3739 } else {
3740 mSizeScale = 0.0f;
3741 }
3742
3743 // Pressure factors.
3744 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003745 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003746 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3747 || mCalibration.pressureCalibration
3748 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3749 if (mCalibration.havePressureScale) {
3750 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003751 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003752 } else if (mRawPointerAxes.pressure.valid
3753 && mRawPointerAxes.pressure.maxValue != 0) {
3754 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3755 }
3756 }
3757
3758 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3759 mOrientedRanges.pressure.source = mSource;
3760 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003761 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003762 mOrientedRanges.pressure.flat = 0;
3763 mOrientedRanges.pressure.fuzz = 0;
3764 mOrientedRanges.pressure.resolution = 0;
3765
3766 // Tilt
3767 mTiltXCenter = 0;
3768 mTiltXScale = 0;
3769 mTiltYCenter = 0;
3770 mTiltYScale = 0;
3771 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3772 if (mHaveTilt) {
3773 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3774 mRawPointerAxes.tiltX.maxValue);
3775 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3776 mRawPointerAxes.tiltY.maxValue);
3777 mTiltXScale = M_PI / 180;
3778 mTiltYScale = M_PI / 180;
3779
3780 mOrientedRanges.haveTilt = true;
3781
3782 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3783 mOrientedRanges.tilt.source = mSource;
3784 mOrientedRanges.tilt.min = 0;
3785 mOrientedRanges.tilt.max = M_PI_2;
3786 mOrientedRanges.tilt.flat = 0;
3787 mOrientedRanges.tilt.fuzz = 0;
3788 mOrientedRanges.tilt.resolution = 0;
3789 }
3790
3791 // Orientation
3792 mOrientationScale = 0;
3793 if (mHaveTilt) {
3794 mOrientedRanges.haveOrientation = true;
3795
3796 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3797 mOrientedRanges.orientation.source = mSource;
3798 mOrientedRanges.orientation.min = -M_PI;
3799 mOrientedRanges.orientation.max = M_PI;
3800 mOrientedRanges.orientation.flat = 0;
3801 mOrientedRanges.orientation.fuzz = 0;
3802 mOrientedRanges.orientation.resolution = 0;
3803 } else if (mCalibration.orientationCalibration !=
3804 Calibration::ORIENTATION_CALIBRATION_NONE) {
3805 if (mCalibration.orientationCalibration
3806 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3807 if (mRawPointerAxes.orientation.valid) {
3808 if (mRawPointerAxes.orientation.maxValue > 0) {
3809 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3810 } else if (mRawPointerAxes.orientation.minValue < 0) {
3811 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3812 } else {
3813 mOrientationScale = 0;
3814 }
3815 }
3816 }
3817
3818 mOrientedRanges.haveOrientation = true;
3819
3820 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3821 mOrientedRanges.orientation.source = mSource;
3822 mOrientedRanges.orientation.min = -M_PI_2;
3823 mOrientedRanges.orientation.max = M_PI_2;
3824 mOrientedRanges.orientation.flat = 0;
3825 mOrientedRanges.orientation.fuzz = 0;
3826 mOrientedRanges.orientation.resolution = 0;
3827 }
3828
3829 // Distance
3830 mDistanceScale = 0;
3831 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3832 if (mCalibration.distanceCalibration
3833 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3834 if (mCalibration.haveDistanceScale) {
3835 mDistanceScale = mCalibration.distanceScale;
3836 } else {
3837 mDistanceScale = 1.0f;
3838 }
3839 }
3840
3841 mOrientedRanges.haveDistance = true;
3842
3843 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3844 mOrientedRanges.distance.source = mSource;
3845 mOrientedRanges.distance.min =
3846 mRawPointerAxes.distance.minValue * mDistanceScale;
3847 mOrientedRanges.distance.max =
3848 mRawPointerAxes.distance.maxValue * mDistanceScale;
3849 mOrientedRanges.distance.flat = 0;
3850 mOrientedRanges.distance.fuzz =
3851 mRawPointerAxes.distance.fuzz * mDistanceScale;
3852 mOrientedRanges.distance.resolution = 0;
3853 }
3854
3855 // Compute oriented precision, scales and ranges.
3856 // Note that the maximum value reported is an inclusive maximum value so it is one
3857 // unit less than the total width or height of surface.
3858 switch (mSurfaceOrientation) {
3859 case DISPLAY_ORIENTATION_90:
3860 case DISPLAY_ORIENTATION_270:
3861 mOrientedXPrecision = mYPrecision;
3862 mOrientedYPrecision = mXPrecision;
3863
3864 mOrientedRanges.x.min = mYTranslate;
3865 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3866 mOrientedRanges.x.flat = 0;
3867 mOrientedRanges.x.fuzz = 0;
3868 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3869
3870 mOrientedRanges.y.min = mXTranslate;
3871 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3872 mOrientedRanges.y.flat = 0;
3873 mOrientedRanges.y.fuzz = 0;
3874 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3875 break;
3876
3877 default:
3878 mOrientedXPrecision = mXPrecision;
3879 mOrientedYPrecision = mYPrecision;
3880
3881 mOrientedRanges.x.min = mXTranslate;
3882 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3883 mOrientedRanges.x.flat = 0;
3884 mOrientedRanges.x.fuzz = 0;
3885 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3886
3887 mOrientedRanges.y.min = mYTranslate;
3888 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3889 mOrientedRanges.y.flat = 0;
3890 mOrientedRanges.y.fuzz = 0;
3891 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3892 break;
3893 }
3894
Jason Gerecke71b16e82014-03-10 09:47:59 -07003895 // Location
3896 updateAffineTransformation();
3897
Michael Wrightd02c5b62014-02-10 15:10:22 -08003898 if (mDeviceMode == DEVICE_MODE_POINTER) {
3899 // Compute pointer gesture detection parameters.
3900 float rawDiagonal = hypotf(rawWidth, rawHeight);
3901 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3902
3903 // Scale movements such that one whole swipe of the touch pad covers a
3904 // given area relative to the diagonal size of the display when no acceleration
3905 // is applied.
3906 // Assume that the touch pad has a square aspect ratio such that movements in
3907 // X and Y of the same number of raw units cover the same physical distance.
3908 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3909 * displayDiagonal / rawDiagonal;
3910 mPointerYMovementScale = mPointerXMovementScale;
3911
3912 // Scale zooms to cover a smaller range of the display than movements do.
3913 // This value determines the area around the pointer that is affected by freeform
3914 // pointer gestures.
3915 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3916 * displayDiagonal / rawDiagonal;
3917 mPointerYZoomScale = mPointerXZoomScale;
3918
3919 // Max width between pointers to detect a swipe gesture is more than some fraction
3920 // of the diagonal axis of the touch pad. Touches that are wider than this are
3921 // translated into freeform gestures.
3922 mPointerGestureMaxSwipeWidth =
3923 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3924
3925 // Abort current pointer usages because the state has changed.
3926 abortPointerUsage(when, 0 /*policyFlags*/);
3927 }
3928
3929 // Inform the dispatcher about the changes.
3930 *outResetNeeded = true;
3931 bumpGeneration();
3932 }
3933}
3934
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003935void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003936 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003937 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3938 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3939 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3940 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003941 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3942 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3943 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3944 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003945 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946}
3947
3948void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003949 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3951
3952 mVirtualKeys.clear();
3953
3954 if (virtualKeyDefinitions.size() == 0) {
3955 return;
3956 }
3957
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3959 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003960 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3961 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003963 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3964 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
3966 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3967 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003968 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003970 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3971 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003972 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3973 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003974 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 }
3976
3977 virtualKey.keyCode = keyCode;
3978 virtualKey.flags = flags;
3979
3980 // convert the key definition's display coordinates into touch coordinates for a hit box
3981 int32_t halfWidth = virtualKeyDefinition.width / 2;
3982 int32_t halfHeight = virtualKeyDefinition.height / 2;
3983
3984 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3985 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3986 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3987 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3988 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3989 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3990 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3991 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003992 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994}
3995
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003996void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003997 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003998 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999
4000 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004001 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004002 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004003 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4004 i, virtualKey.scanCode, virtualKey.keyCode,
4005 virtualKey.hitLeft, virtualKey.hitRight,
4006 virtualKey.hitTop, virtualKey.hitBottom);
4007 }
4008 }
4009}
4010
4011void TouchInputMapper::parseCalibration() {
4012 const PropertyMap& in = getDevice()->getConfiguration();
4013 Calibration& out = mCalibration;
4014
4015 // Size
4016 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4017 String8 sizeCalibrationString;
4018 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4019 if (sizeCalibrationString == "none") {
4020 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4021 } else if (sizeCalibrationString == "geometric") {
4022 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4023 } else if (sizeCalibrationString == "diameter") {
4024 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4025 } else if (sizeCalibrationString == "box") {
4026 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4027 } else if (sizeCalibrationString == "area") {
4028 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4029 } else if (sizeCalibrationString != "default") {
4030 ALOGW("Invalid value for touch.size.calibration: '%s'",
4031 sizeCalibrationString.string());
4032 }
4033 }
4034
4035 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4036 out.sizeScale);
4037 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4038 out.sizeBias);
4039 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4040 out.sizeIsSummed);
4041
4042 // Pressure
4043 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4044 String8 pressureCalibrationString;
4045 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4046 if (pressureCalibrationString == "none") {
4047 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4048 } else if (pressureCalibrationString == "physical") {
4049 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4050 } else if (pressureCalibrationString == "amplitude") {
4051 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4052 } else if (pressureCalibrationString != "default") {
4053 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4054 pressureCalibrationString.string());
4055 }
4056 }
4057
4058 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4059 out.pressureScale);
4060
4061 // Orientation
4062 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4063 String8 orientationCalibrationString;
4064 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4065 if (orientationCalibrationString == "none") {
4066 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4067 } else if (orientationCalibrationString == "interpolated") {
4068 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4069 } else if (orientationCalibrationString == "vector") {
4070 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4071 } else if (orientationCalibrationString != "default") {
4072 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4073 orientationCalibrationString.string());
4074 }
4075 }
4076
4077 // Distance
4078 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4079 String8 distanceCalibrationString;
4080 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4081 if (distanceCalibrationString == "none") {
4082 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4083 } else if (distanceCalibrationString == "scaled") {
4084 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4085 } else if (distanceCalibrationString != "default") {
4086 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4087 distanceCalibrationString.string());
4088 }
4089 }
4090
4091 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4092 out.distanceScale);
4093
4094 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4095 String8 coverageCalibrationString;
4096 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4097 if (coverageCalibrationString == "none") {
4098 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4099 } else if (coverageCalibrationString == "box") {
4100 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4101 } else if (coverageCalibrationString != "default") {
4102 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4103 coverageCalibrationString.string());
4104 }
4105 }
4106}
4107
4108void TouchInputMapper::resolveCalibration() {
4109 // Size
4110 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4111 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4112 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4113 }
4114 } else {
4115 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4116 }
4117
4118 // Pressure
4119 if (mRawPointerAxes.pressure.valid) {
4120 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4121 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4122 }
4123 } else {
4124 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4125 }
4126
4127 // Orientation
4128 if (mRawPointerAxes.orientation.valid) {
4129 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4130 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4131 }
4132 } else {
4133 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4134 }
4135
4136 // Distance
4137 if (mRawPointerAxes.distance.valid) {
4138 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4139 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4140 }
4141 } else {
4142 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4143 }
4144
4145 // Coverage
4146 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4147 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4148 }
4149}
4150
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151void TouchInputMapper::dumpCalibration(std::string& dump) {
4152 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153
4154 // Size
4155 switch (mCalibration.sizeCalibration) {
4156 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 break;
4159 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 break;
4162 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 break;
4165 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004166 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 break;
4168 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 break;
4171 default:
4172 ALOG_ASSERT(false);
4173 }
4174
4175 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004176 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004177 mCalibration.sizeScale);
4178 }
4179
4180 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 mCalibration.sizeBias);
4183 }
4184
4185 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004186 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 toString(mCalibration.sizeIsSummed));
4188 }
4189
4190 // Pressure
4191 switch (mCalibration.pressureCalibration) {
4192 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 break;
4195 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004196 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 break;
4198 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 break;
4201 default:
4202 ALOG_ASSERT(false);
4203 }
4204
4205 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 mCalibration.pressureScale);
4208 }
4209
4210 // Orientation
4211 switch (mCalibration.orientationCalibration) {
4212 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 break;
4215 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 break;
4218 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004219 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220 break;
4221 default:
4222 ALOG_ASSERT(false);
4223 }
4224
4225 // Distance
4226 switch (mCalibration.distanceCalibration) {
4227 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004228 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 break;
4230 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004232 break;
4233 default:
4234 ALOG_ASSERT(false);
4235 }
4236
4237 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004238 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004239 mCalibration.distanceScale);
4240 }
4241
4242 switch (mCalibration.coverageCalibration) {
4243 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004244 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 break;
4246 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004247 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248 break;
4249 default:
4250 ALOG_ASSERT(false);
4251 }
4252}
4253
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004254void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4255 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004256
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004257 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4258 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4259 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4260 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4261 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4262 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004263}
4264
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004265void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004266 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4267 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004268}
4269
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270void TouchInputMapper::reset(nsecs_t when) {
4271 mCursorButtonAccumulator.reset(getDevice());
4272 mCursorScrollAccumulator.reset(getDevice());
4273 mTouchButtonAccumulator.reset(getDevice());
4274
4275 mPointerVelocityControl.reset();
4276 mWheelXVelocityControl.reset();
4277 mWheelYVelocityControl.reset();
4278
Michael Wright842500e2015-03-13 17:32:02 -07004279 mRawStatesPending.clear();
4280 mCurrentRawState.clear();
4281 mCurrentCookedState.clear();
4282 mLastRawState.clear();
4283 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284 mPointerUsage = POINTER_USAGE_NONE;
4285 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004286 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004287 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 mDownTime = 0;
4289
4290 mCurrentVirtualKey.down = false;
4291
4292 mPointerGesture.reset();
4293 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004294 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004295
Yi Kong9b14ac62018-07-17 13:48:38 -07004296 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4298 mPointerController->clearSpots();
4299 }
4300
4301 InputMapper::reset(when);
4302}
4303
Michael Wright842500e2015-03-13 17:32:02 -07004304void TouchInputMapper::resetExternalStylus() {
4305 mExternalStylusState.clear();
4306 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004307 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004308 mExternalStylusDataPending = false;
4309}
4310
Michael Wright43fd19f2015-04-21 19:02:58 +01004311void TouchInputMapper::clearStylusDataPendingFlags() {
4312 mExternalStylusDataPending = false;
4313 mExternalStylusFusionTimeout = LLONG_MAX;
4314}
4315
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004316void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4317 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4318 nsecs_t latency = now - evdevTime;
4319 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4320 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4321 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4322 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
Siarhei Vishniakou05247bb2019-03-22 17:11:21 -07004323 mStatistics.min, mStatistics.max,
4324 mStatistics.mean(), mStatistics.stdev(), mStatistics.count);
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004325 mStatistics.reset(now);
4326 }
4327}
4328
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329void TouchInputMapper::process(const RawEvent* rawEvent) {
4330 mCursorButtonAccumulator.process(rawEvent);
4331 mCursorScrollAccumulator.process(rawEvent);
4332 mTouchButtonAccumulator.process(rawEvent);
4333
4334 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004335 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336 sync(rawEvent->when);
4337 }
4338}
4339
4340void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004341 const RawState* last = mRawStatesPending.empty() ?
4342 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004343
4344 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004345 mRawStatesPending.emplace_back();
4346
4347 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004348 next->clear();
4349 next->when = when;
4350
Michael Wrightd02c5b62014-02-10 15:10:22 -08004351 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004352 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353 | mCursorButtonAccumulator.getButtonState();
4354
Michael Wright842500e2015-03-13 17:32:02 -07004355 // Sync scroll
4356 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4357 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 mCursorScrollAccumulator.finishSync();
4359
Michael Wright842500e2015-03-13 17:32:02 -07004360 // Sync touch
4361 syncTouch(when, next);
4362
4363 // Assign pointer ids.
4364 if (!mHavePointerIds) {
4365 assignPointerIds(last, next);
4366 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004367
4368#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004369 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4370 "hovering ids 0x%08x -> 0x%08x",
4371 last->rawPointerData.pointerCount,
4372 next->rawPointerData.pointerCount,
4373 last->rawPointerData.touchingIdBits.value,
4374 next->rawPointerData.touchingIdBits.value,
4375 last->rawPointerData.hoveringIdBits.value,
4376 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004377#endif
4378
Michael Wright842500e2015-03-13 17:32:02 -07004379 processRawTouches(false /*timeout*/);
4380}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004381
Michael Wright842500e2015-03-13 17:32:02 -07004382void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4384 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004385 mCurrentRawState.clear();
4386 mRawStatesPending.clear();
4387 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 }
4389
Michael Wright842500e2015-03-13 17:32:02 -07004390 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4391 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4392 // touching the current state will only observe the events that have been dispatched to the
4393 // rest of the pipeline.
4394 const size_t N = mRawStatesPending.size();
4395 size_t count;
4396 for(count = 0; count < N; count++) {
4397 const RawState& next = mRawStatesPending[count];
4398
4399 // A failure to assign the stylus id means that we're waiting on stylus data
4400 // and so should defer the rest of the pipeline.
4401 if (assignExternalStylusId(next, timeout)) {
4402 break;
4403 }
4404
4405 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004406 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004407 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004408 if (mCurrentRawState.when < mLastRawState.when) {
4409 mCurrentRawState.when = mLastRawState.when;
4410 }
Michael Wright842500e2015-03-13 17:32:02 -07004411 cookAndDispatch(mCurrentRawState.when);
4412 }
4413 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004414 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004415 }
4416
Michael Wright842500e2015-03-13 17:32:02 -07004417 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004418 if (timeout) {
4419 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4420 clearStylusDataPendingFlags();
4421 mCurrentRawState.copyFrom(mLastRawState);
4422#if DEBUG_STYLUS_FUSION
4423 ALOGD("Timeout expired, synthesizing event with new stylus data");
4424#endif
4425 cookAndDispatch(when);
4426 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4427 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4428 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4429 }
Michael Wright842500e2015-03-13 17:32:02 -07004430 }
4431}
4432
4433void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4434 // Always start with a clean state.
4435 mCurrentCookedState.clear();
4436
4437 // Apply stylus buttons to current raw state.
4438 applyExternalStylusButtonState(when);
4439
4440 // Handle policy on initial down or hover events.
4441 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4442 && mCurrentRawState.rawPointerData.pointerCount != 0;
4443
4444 uint32_t policyFlags = 0;
4445 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4446 if (initialDown || buttonsPressed) {
4447 // If this is a touch screen, hide the pointer on an initial down.
4448 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4449 getContext()->fadePointer();
4450 }
4451
4452 if (mParameters.wake) {
4453 policyFlags |= POLICY_FLAG_WAKE;
4454 }
4455 }
4456
4457 // Consume raw off-screen touches before cooking pointer data.
4458 // If touches are consumed, subsequent code will not receive any pointer data.
4459 if (consumeRawTouches(when, policyFlags)) {
4460 mCurrentRawState.rawPointerData.clear();
4461 }
4462
4463 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4464 // with cooked pointer data that has the same ids and indices as the raw data.
4465 // The following code can use either the raw or cooked data, as needed.
4466 cookPointerData();
4467
4468 // Apply stylus pressure to current cooked state.
4469 applyExternalStylusTouchState(when);
4470
4471 // Synthesize key down from raw buttons if needed.
4472 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004473 mViewport.displayId, policyFlags,
4474 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004475
4476 // Dispatch the touches either directly or by translation through a pointer on screen.
4477 if (mDeviceMode == DEVICE_MODE_POINTER) {
4478 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4479 !idBits.isEmpty(); ) {
4480 uint32_t id = idBits.clearFirstMarkedBit();
4481 const RawPointerData::Pointer& pointer =
4482 mCurrentRawState.rawPointerData.pointerForId(id);
4483 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4484 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4485 mCurrentCookedState.stylusIdBits.markBit(id);
4486 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4487 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4488 mCurrentCookedState.fingerIdBits.markBit(id);
4489 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4490 mCurrentCookedState.mouseIdBits.markBit(id);
4491 }
4492 }
4493 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4494 !idBits.isEmpty(); ) {
4495 uint32_t id = idBits.clearFirstMarkedBit();
4496 const RawPointerData::Pointer& pointer =
4497 mCurrentRawState.rawPointerData.pointerForId(id);
4498 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4499 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4500 mCurrentCookedState.stylusIdBits.markBit(id);
4501 }
4502 }
4503
4504 // Stylus takes precedence over all tools, then mouse, then finger.
4505 PointerUsage pointerUsage = mPointerUsage;
4506 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4507 mCurrentCookedState.mouseIdBits.clear();
4508 mCurrentCookedState.fingerIdBits.clear();
4509 pointerUsage = POINTER_USAGE_STYLUS;
4510 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4511 mCurrentCookedState.fingerIdBits.clear();
4512 pointerUsage = POINTER_USAGE_MOUSE;
4513 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4514 isPointerDown(mCurrentRawState.buttonState)) {
4515 pointerUsage = POINTER_USAGE_GESTURES;
4516 }
4517
4518 dispatchPointerUsage(when, policyFlags, pointerUsage);
4519 } else {
4520 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004521 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004522 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4523 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4524
4525 mPointerController->setButtonState(mCurrentRawState.buttonState);
4526 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4527 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004528 mCurrentCookedState.cookedPointerData.touchingIdBits,
4529 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004530 }
4531
Michael Wright8e812822015-06-22 16:18:21 +01004532 if (!mCurrentMotionAborted) {
4533 dispatchButtonRelease(when, policyFlags);
4534 dispatchHoverExit(when, policyFlags);
4535 dispatchTouches(when, policyFlags);
4536 dispatchHoverEnterAndMove(when, policyFlags);
4537 dispatchButtonPress(when, policyFlags);
4538 }
4539
4540 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4541 mCurrentMotionAborted = false;
4542 }
Michael Wright842500e2015-03-13 17:32:02 -07004543 }
4544
4545 // Synthesize key up from raw buttons if needed.
4546 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004547 mViewport.displayId, policyFlags,
4548 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004549
4550 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004551 mCurrentRawState.rawVScroll = 0;
4552 mCurrentRawState.rawHScroll = 0;
4553
4554 // Copy current touch to last touch in preparation for the next cycle.
4555 mLastRawState.copyFrom(mCurrentRawState);
4556 mLastCookedState.copyFrom(mCurrentCookedState);
4557}
4558
4559void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004560 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004561 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4562 }
4563}
4564
4565void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004566 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4567 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004568
Michael Wright53dca3a2015-04-23 17:39:53 +01004569 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4570 float pressure = mExternalStylusState.pressure;
4571 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4572 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4573 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4574 }
4575 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4576 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4577
4578 PointerProperties& properties =
4579 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004580 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4581 properties.toolType = mExternalStylusState.toolType;
4582 }
4583 }
4584}
4585
4586bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4587 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4588 return false;
4589 }
4590
4591 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4592 && state.rawPointerData.pointerCount != 0;
4593 if (initialDown) {
4594 if (mExternalStylusState.pressure != 0.0f) {
4595#if DEBUG_STYLUS_FUSION
4596 ALOGD("Have both stylus and touch data, beginning fusion");
4597#endif
4598 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4599 } else if (timeout) {
4600#if DEBUG_STYLUS_FUSION
4601 ALOGD("Timeout expired, assuming touch is not a stylus.");
4602#endif
4603 resetExternalStylus();
4604 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004605 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4606 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004607 }
4608#if DEBUG_STYLUS_FUSION
4609 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004610 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004611#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004612 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004613 return true;
4614 }
4615 }
4616
4617 // Check if the stylus pointer has gone up.
4618 if (mExternalStylusId != -1 &&
4619 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4620#if DEBUG_STYLUS_FUSION
4621 ALOGD("Stylus pointer is going up");
4622#endif
4623 mExternalStylusId = -1;
4624 }
4625
4626 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627}
4628
4629void TouchInputMapper::timeoutExpired(nsecs_t when) {
4630 if (mDeviceMode == DEVICE_MODE_POINTER) {
4631 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4632 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4633 }
Michael Wright842500e2015-03-13 17:32:02 -07004634 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004635 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004636 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004637 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4638 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004639 }
4640 }
4641}
4642
4643void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004644 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004645 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004646 // We're either in the middle of a fused stream of data or we're waiting on data before
4647 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4648 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004649 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004650 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651 }
4652}
4653
4654bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4655 // Check for release of a virtual key.
4656 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004657 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004658 // Pointer went up while virtual key was down.
4659 mCurrentVirtualKey.down = false;
4660 if (!mCurrentVirtualKey.ignored) {
4661#if DEBUG_VIRTUAL_KEYS
4662 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4663 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4664#endif
4665 dispatchVirtualKey(when, policyFlags,
4666 AKEY_EVENT_ACTION_UP,
4667 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4668 }
4669 return true;
4670 }
4671
Michael Wright842500e2015-03-13 17:32:02 -07004672 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4673 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4674 const RawPointerData::Pointer& pointer =
4675 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4677 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4678 // Pointer is still within the space of the virtual key.
4679 return true;
4680 }
4681 }
4682
4683 // Pointer left virtual key area or another pointer also went down.
4684 // Send key cancellation but do not consume the touch yet.
4685 // This is useful when the user swipes through from the virtual key area
4686 // into the main display surface.
4687 mCurrentVirtualKey.down = false;
4688 if (!mCurrentVirtualKey.ignored) {
4689#if DEBUG_VIRTUAL_KEYS
4690 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4691 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4692#endif
4693 dispatchVirtualKey(when, policyFlags,
4694 AKEY_EVENT_ACTION_UP,
4695 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4696 | AKEY_EVENT_FLAG_CANCELED);
4697 }
4698 }
4699
Michael Wright842500e2015-03-13 17:32:02 -07004700 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4701 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004702 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004703 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4704 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004705 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4706 // If exactly one pointer went down, check for virtual key hit.
4707 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004708 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004709 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4710 if (virtualKey) {
4711 mCurrentVirtualKey.down = true;
4712 mCurrentVirtualKey.downTime = when;
4713 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4714 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4715 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4716 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4717
4718 if (!mCurrentVirtualKey.ignored) {
4719#if DEBUG_VIRTUAL_KEYS
4720 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4721 mCurrentVirtualKey.keyCode,
4722 mCurrentVirtualKey.scanCode);
4723#endif
4724 dispatchVirtualKey(when, policyFlags,
4725 AKEY_EVENT_ACTION_DOWN,
4726 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4727 }
4728 }
4729 }
4730 return true;
4731 }
4732 }
4733
4734 // Disable all virtual key touches that happen within a short time interval of the
4735 // most recent touch within the screen area. The idea is to filter out stray
4736 // virtual key presses when interacting with the touch screen.
4737 //
4738 // Problems we're trying to solve:
4739 //
4740 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4741 // virtual key area that is implemented by a separate touch panel and accidentally
4742 // triggers a virtual key.
4743 //
4744 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4745 // area and accidentally triggers a virtual key. This often happens when virtual keys
4746 // are layed out below the screen near to where the on screen keyboard's space bar
4747 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004748 if (mConfig.virtualKeyQuietTime > 0 &&
4749 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004750 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4751 }
4752 return false;
4753}
4754
4755void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4756 int32_t keyEventAction, int32_t keyEventFlags) {
4757 int32_t keyCode = mCurrentVirtualKey.keyCode;
4758 int32_t scanCode = mCurrentVirtualKey.scanCode;
4759 nsecs_t downTime = mCurrentVirtualKey.downTime;
4760 int32_t metaState = mContext->getGlobalMetaState();
4761 policyFlags |= POLICY_FLAG_VIRTUAL;
4762
Prabir Pradhan42611e02018-11-27 14:04:02 -08004763 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4764 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004765 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004766 getListener()->notifyKey(&args);
4767}
4768
Michael Wright8e812822015-06-22 16:18:21 +01004769void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4770 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4771 if (!currentIdBits.isEmpty()) {
4772 int32_t metaState = getContext()->getGlobalMetaState();
4773 int32_t buttonState = mCurrentCookedState.buttonState;
4774 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4775 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4776 mCurrentCookedState.cookedPointerData.pointerProperties,
4777 mCurrentCookedState.cookedPointerData.pointerCoords,
4778 mCurrentCookedState.cookedPointerData.idToIndex,
4779 currentIdBits, -1,
4780 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4781 mCurrentMotionAborted = true;
4782 }
4783}
4784
Michael Wrightd02c5b62014-02-10 15:10:22 -08004785void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004786 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4787 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004788 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004789 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790
4791 if (currentIdBits == lastIdBits) {
4792 if (!currentIdBits.isEmpty()) {
4793 // No pointer id changes so this is a move event.
4794 // The listener takes care of batching moves so we don't have to deal with that here.
4795 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004796 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004798 mCurrentCookedState.cookedPointerData.pointerProperties,
4799 mCurrentCookedState.cookedPointerData.pointerCoords,
4800 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 currentIdBits, -1,
4802 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4803 }
4804 } else {
4805 // There may be pointers going up and pointers going down and pointers moving
4806 // all at the same time.
4807 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4808 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4809 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4810 BitSet32 dispatchedIdBits(lastIdBits.value);
4811
4812 // Update last coordinates of pointers that have moved so that we observe the new
4813 // pointer positions at the same time as other pointers that have just gone up.
4814 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004815 mCurrentCookedState.cookedPointerData.pointerProperties,
4816 mCurrentCookedState.cookedPointerData.pointerCoords,
4817 mCurrentCookedState.cookedPointerData.idToIndex,
4818 mLastCookedState.cookedPointerData.pointerProperties,
4819 mLastCookedState.cookedPointerData.pointerCoords,
4820 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004821 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004822 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 moveNeeded = true;
4824 }
4825
4826 // Dispatch pointer up events.
4827 while (!upIdBits.isEmpty()) {
4828 uint32_t upId = upIdBits.clearFirstMarkedBit();
4829
4830 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004831 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004832 mLastCookedState.cookedPointerData.pointerProperties,
4833 mLastCookedState.cookedPointerData.pointerCoords,
4834 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004835 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004836 dispatchedIdBits.clearBit(upId);
4837 }
4838
4839 // Dispatch move events if any of the remaining pointers moved from their old locations.
4840 // Although applications receive new locations as part of individual pointer up
4841 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004842 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004843 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4844 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004845 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004846 mCurrentCookedState.cookedPointerData.pointerProperties,
4847 mCurrentCookedState.cookedPointerData.pointerCoords,
4848 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004849 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 }
4851
4852 // Dispatch pointer down events using the new pointer locations.
4853 while (!downIdBits.isEmpty()) {
4854 uint32_t downId = downIdBits.clearFirstMarkedBit();
4855 dispatchedIdBits.markBit(downId);
4856
4857 if (dispatchedIdBits.count() == 1) {
4858 // First pointer is going down. Set down time.
4859 mDownTime = when;
4860 }
4861
4862 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004863 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004864 mCurrentCookedState.cookedPointerData.pointerProperties,
4865 mCurrentCookedState.cookedPointerData.pointerCoords,
4866 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004867 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 }
4869 }
4870}
4871
4872void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4873 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004874 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4875 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 int32_t metaState = getContext()->getGlobalMetaState();
4877 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004878 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
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,
Michael Wright842500e2015-03-13 17:32:02 -07004895 mCurrentCookedState.cookedPointerData.pointerProperties,
4896 mCurrentCookedState.cookedPointerData.pointerCoords,
4897 mCurrentCookedState.cookedPointerData.idToIndex,
4898 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4900 mSentHoverEnter = true;
4901 }
4902
4903 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004904 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004905 mCurrentRawState.buttonState, 0,
4906 mCurrentCookedState.cookedPointerData.pointerProperties,
4907 mCurrentCookedState.cookedPointerData.pointerCoords,
4908 mCurrentCookedState.cookedPointerData.idToIndex,
4909 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4911 }
4912}
4913
Michael Wright7b159c92015-05-14 14:48:03 +01004914void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4915 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4916 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4917 const int32_t metaState = getContext()->getGlobalMetaState();
4918 int32_t buttonState = mLastCookedState.buttonState;
4919 while (!releasedButtons.isEmpty()) {
4920 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4921 buttonState &= ~actionButton;
4922 dispatchMotion(when, policyFlags, mSource,
4923 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4924 0, metaState, buttonState, 0,
4925 mCurrentCookedState.cookedPointerData.pointerProperties,
4926 mCurrentCookedState.cookedPointerData.pointerCoords,
4927 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4928 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4929 }
4930}
4931
4932void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4933 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4934 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4935 const int32_t metaState = getContext()->getGlobalMetaState();
4936 int32_t buttonState = mLastCookedState.buttonState;
4937 while (!pressedButtons.isEmpty()) {
4938 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4939 buttonState |= actionButton;
4940 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4941 0, metaState, buttonState, 0,
4942 mCurrentCookedState.cookedPointerData.pointerProperties,
4943 mCurrentCookedState.cookedPointerData.pointerCoords,
4944 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4945 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4946 }
4947}
4948
4949const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4950 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4951 return cookedPointerData.touchingIdBits;
4952 }
4953 return cookedPointerData.hoveringIdBits;
4954}
4955
Michael Wrightd02c5b62014-02-10 15:10:22 -08004956void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004957 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004958
Michael Wright842500e2015-03-13 17:32:02 -07004959 mCurrentCookedState.cookedPointerData.clear();
4960 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4961 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4962 mCurrentRawState.rawPointerData.hoveringIdBits;
4963 mCurrentCookedState.cookedPointerData.touchingIdBits =
4964 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004965
Michael Wright7b159c92015-05-14 14:48:03 +01004966 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4967 mCurrentCookedState.buttonState = 0;
4968 } else {
4969 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4970 }
4971
Michael Wrightd02c5b62014-02-10 15:10:22 -08004972 // Walk through the the active pointers and map device coordinates onto
4973 // surface coordinates and adjust for display orientation.
4974 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004975 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004976
4977 // Size
4978 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4979 switch (mCalibration.sizeCalibration) {
4980 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4981 case Calibration::SIZE_CALIBRATION_DIAMETER:
4982 case Calibration::SIZE_CALIBRATION_BOX:
4983 case Calibration::SIZE_CALIBRATION_AREA:
4984 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4985 touchMajor = in.touchMajor;
4986 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4987 toolMajor = in.toolMajor;
4988 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4989 size = mRawPointerAxes.touchMinor.valid
4990 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4991 } else if (mRawPointerAxes.touchMajor.valid) {
4992 toolMajor = touchMajor = in.touchMajor;
4993 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4994 ? in.touchMinor : in.touchMajor;
4995 size = mRawPointerAxes.touchMinor.valid
4996 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4997 } else if (mRawPointerAxes.toolMajor.valid) {
4998 touchMajor = toolMajor = in.toolMajor;
4999 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5000 ? in.toolMinor : in.toolMajor;
5001 size = mRawPointerAxes.toolMinor.valid
5002 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5003 } else {
5004 ALOG_ASSERT(false, "No touch or tool axes. "
5005 "Size calibration should have been resolved to NONE.");
5006 touchMajor = 0;
5007 touchMinor = 0;
5008 toolMajor = 0;
5009 toolMinor = 0;
5010 size = 0;
5011 }
5012
5013 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005014 uint32_t touchingCount =
5015 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005016 if (touchingCount > 1) {
5017 touchMajor /= touchingCount;
5018 touchMinor /= touchingCount;
5019 toolMajor /= touchingCount;
5020 toolMinor /= touchingCount;
5021 size /= touchingCount;
5022 }
5023 }
5024
5025 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5026 touchMajor *= mGeometricScale;
5027 touchMinor *= mGeometricScale;
5028 toolMajor *= mGeometricScale;
5029 toolMinor *= mGeometricScale;
5030 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5031 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5032 touchMinor = touchMajor;
5033 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5034 toolMinor = toolMajor;
5035 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5036 touchMinor = touchMajor;
5037 toolMinor = toolMajor;
5038 }
5039
5040 mCalibration.applySizeScaleAndBias(&touchMajor);
5041 mCalibration.applySizeScaleAndBias(&touchMinor);
5042 mCalibration.applySizeScaleAndBias(&toolMajor);
5043 mCalibration.applySizeScaleAndBias(&toolMinor);
5044 size *= mSizeScale;
5045 break;
5046 default:
5047 touchMajor = 0;
5048 touchMinor = 0;
5049 toolMajor = 0;
5050 toolMinor = 0;
5051 size = 0;
5052 break;
5053 }
5054
5055 // Pressure
5056 float pressure;
5057 switch (mCalibration.pressureCalibration) {
5058 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5059 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5060 pressure = in.pressure * mPressureScale;
5061 break;
5062 default:
5063 pressure = in.isHovering ? 0 : 1;
5064 break;
5065 }
5066
5067 // Tilt and Orientation
5068 float tilt;
5069 float orientation;
5070 if (mHaveTilt) {
5071 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5072 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5073 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5074 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5075 } else {
5076 tilt = 0;
5077
5078 switch (mCalibration.orientationCalibration) {
5079 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5080 orientation = in.orientation * mOrientationScale;
5081 break;
5082 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5083 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5084 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5085 if (c1 != 0 || c2 != 0) {
5086 orientation = atan2f(c1, c2) * 0.5f;
5087 float confidence = hypotf(c1, c2);
5088 float scale = 1.0f + confidence / 16.0f;
5089 touchMajor *= scale;
5090 touchMinor /= scale;
5091 toolMajor *= scale;
5092 toolMinor /= scale;
5093 } else {
5094 orientation = 0;
5095 }
5096 break;
5097 }
5098 default:
5099 orientation = 0;
5100 }
5101 }
5102
5103 // Distance
5104 float distance;
5105 switch (mCalibration.distanceCalibration) {
5106 case Calibration::DISTANCE_CALIBRATION_SCALED:
5107 distance = in.distance * mDistanceScale;
5108 break;
5109 default:
5110 distance = 0;
5111 }
5112
5113 // Coverage
5114 int32_t rawLeft, rawTop, rawRight, rawBottom;
5115 switch (mCalibration.coverageCalibration) {
5116 case Calibration::COVERAGE_CALIBRATION_BOX:
5117 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5118 rawRight = in.toolMinor & 0x0000ffff;
5119 rawBottom = in.toolMajor & 0x0000ffff;
5120 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5121 break;
5122 default:
5123 rawLeft = rawTop = rawRight = rawBottom = 0;
5124 break;
5125 }
5126
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005127 // Adjust X,Y coords for device calibration
5128 // TODO: Adjust coverage coords?
5129 float xTransformed = in.x, yTransformed = in.y;
5130 mAffineTransform.applyTo(xTransformed, yTransformed);
5131
5132 // Adjust X, Y, and coverage coords for surface orientation.
5133 float x, y;
5134 float left, top, right, bottom;
5135
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 switch (mSurfaceOrientation) {
5137 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005138 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5139 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5141 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5142 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5143 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5144 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005145 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5147 }
5148 break;
5149 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005150 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005151 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005152 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5153 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5155 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5156 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005157 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5159 }
5160 break;
5161 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005162 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005163 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005164 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5165 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005166 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5167 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5168 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005169 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5171 }
5172 break;
5173 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005174 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5175 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5177 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5178 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5179 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5180 break;
5181 }
5182
5183 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005184 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 out.clear();
5186 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5187 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5188 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5189 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5190 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5191 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5192 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5194 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5195 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5196 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5197 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5198 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5199 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5200 } else {
5201 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5202 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5203 }
5204
5205 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005206 PointerProperties& properties =
5207 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005208 uint32_t id = in.id;
5209 properties.clear();
5210 properties.id = id;
5211 properties.toolType = in.toolType;
5212
5213 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005214 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005215 }
5216}
5217
5218void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5219 PointerUsage pointerUsage) {
5220 if (pointerUsage != mPointerUsage) {
5221 abortPointerUsage(when, policyFlags);
5222 mPointerUsage = pointerUsage;
5223 }
5224
5225 switch (mPointerUsage) {
5226 case POINTER_USAGE_GESTURES:
5227 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5228 break;
5229 case POINTER_USAGE_STYLUS:
5230 dispatchPointerStylus(when, policyFlags);
5231 break;
5232 case POINTER_USAGE_MOUSE:
5233 dispatchPointerMouse(when, policyFlags);
5234 break;
5235 default:
5236 break;
5237 }
5238}
5239
5240void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5241 switch (mPointerUsage) {
5242 case POINTER_USAGE_GESTURES:
5243 abortPointerGestures(when, policyFlags);
5244 break;
5245 case POINTER_USAGE_STYLUS:
5246 abortPointerStylus(when, policyFlags);
5247 break;
5248 case POINTER_USAGE_MOUSE:
5249 abortPointerMouse(when, policyFlags);
5250 break;
5251 default:
5252 break;
5253 }
5254
5255 mPointerUsage = POINTER_USAGE_NONE;
5256}
5257
5258void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5259 bool isTimeout) {
5260 // Update current gesture coordinates.
5261 bool cancelPreviousGesture, finishPreviousGesture;
5262 bool sendEvents = preparePointerGestures(when,
5263 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5264 if (!sendEvents) {
5265 return;
5266 }
5267 if (finishPreviousGesture) {
5268 cancelPreviousGesture = false;
5269 }
5270
5271 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005272 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5273 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005274 if (finishPreviousGesture || cancelPreviousGesture) {
5275 mPointerController->clearSpots();
5276 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005277
5278 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5279 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5280 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005281 mPointerGesture.currentGestureIdBits,
5282 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005283 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005284 } else {
5285 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5286 }
5287
5288 // Show or hide the pointer if needed.
5289 switch (mPointerGesture.currentGestureMode) {
5290 case PointerGesture::NEUTRAL:
5291 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005292 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5293 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005294 // Remind the user of where the pointer is after finishing a gesture with spots.
5295 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5296 }
5297 break;
5298 case PointerGesture::TAP:
5299 case PointerGesture::TAP_DRAG:
5300 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5301 case PointerGesture::HOVER:
5302 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005303 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 // Unfade the pointer when the current gesture manipulates the
5305 // area directly under the pointer.
5306 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5307 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005308 case PointerGesture::FREEFORM:
5309 // Fade the pointer when the current gesture manipulates a different
5310 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005311 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5313 } else {
5314 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5315 }
5316 break;
5317 }
5318
5319 // Send events!
5320 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005321 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322
5323 // Update last coordinates of pointers that have moved so that we observe the new
5324 // pointer positions at the same time as other pointers that have just gone up.
5325 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5326 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5327 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5328 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5329 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5330 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5331 bool moveNeeded = false;
5332 if (down && !cancelPreviousGesture && !finishPreviousGesture
5333 && !mPointerGesture.lastGestureIdBits.isEmpty()
5334 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5335 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5336 & mPointerGesture.lastGestureIdBits.value);
5337 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5338 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5339 mPointerGesture.lastGestureProperties,
5340 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5341 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005342 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 moveNeeded = true;
5344 }
5345 }
5346
5347 // Send motion events for all pointers that went up or were canceled.
5348 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5349 if (!dispatchedGestureIdBits.isEmpty()) {
5350 if (cancelPreviousGesture) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005351 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5352 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5353 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5354 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5355 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005356
5357 dispatchedGestureIdBits.clear();
5358 } else {
5359 BitSet32 upGestureIdBits;
5360 if (finishPreviousGesture) {
5361 upGestureIdBits = dispatchedGestureIdBits;
5362 } else {
5363 upGestureIdBits.value = dispatchedGestureIdBits.value
5364 & ~mPointerGesture.currentGestureIdBits.value;
5365 }
5366 while (!upGestureIdBits.isEmpty()) {
5367 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5368
5369 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005370 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005371 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5372 mPointerGesture.lastGestureProperties,
5373 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5374 dispatchedGestureIdBits, id,
5375 0, 0, mPointerGesture.downTime);
5376
5377 dispatchedGestureIdBits.clearBit(id);
5378 }
5379 }
5380 }
5381
5382 // Send motion events for all pointers that moved.
5383 if (moveNeeded) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005384 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5385 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5386 mPointerGesture.currentGestureProperties,
5387 mPointerGesture.currentGestureCoords,
5388 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5389 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 }
5391
5392 // Send motion events for all pointers that went down.
5393 if (down) {
5394 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5395 & ~dispatchedGestureIdBits.value);
5396 while (!downGestureIdBits.isEmpty()) {
5397 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5398 dispatchedGestureIdBits.markBit(id);
5399
5400 if (dispatchedGestureIdBits.count() == 1) {
5401 mPointerGesture.downTime = when;
5402 }
5403
5404 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005405 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005406 mPointerGesture.currentGestureProperties,
5407 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5408 dispatchedGestureIdBits, id,
5409 0, 0, mPointerGesture.downTime);
5410 }
5411 }
5412
5413 // Send motion events for hover.
5414 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005415 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5416 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5417 mPointerGesture.currentGestureProperties,
5418 mPointerGesture.currentGestureCoords,
5419 mPointerGesture.currentGestureIdToIndex,
5420 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 } else if (dispatchedGestureIdBits.isEmpty()
5422 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5423 // Synthesize a hover move event after all pointers go up to indicate that
5424 // the pointer is hovering again even if the user is not currently touching
5425 // the touch pad. This ensures that a view will receive a fresh hover enter
5426 // event after a tap.
5427 float x, y;
5428 mPointerController->getPosition(&x, &y);
5429
5430 PointerProperties pointerProperties;
5431 pointerProperties.clear();
5432 pointerProperties.id = 0;
5433 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5434
5435 PointerCoords pointerCoords;
5436 pointerCoords.clear();
5437 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5438 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5439
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005440 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005441 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5442 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5443 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005444 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
5445 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 getListener()->notifyMotion(&args);
5447 }
5448
5449 // Update state.
5450 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5451 if (!down) {
5452 mPointerGesture.lastGestureIdBits.clear();
5453 } else {
5454 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5455 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5456 uint32_t id = idBits.clearFirstMarkedBit();
5457 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5458 mPointerGesture.lastGestureProperties[index].copyFrom(
5459 mPointerGesture.currentGestureProperties[index]);
5460 mPointerGesture.lastGestureCoords[index].copyFrom(
5461 mPointerGesture.currentGestureCoords[index]);
5462 mPointerGesture.lastGestureIdToIndex[id] = index;
5463 }
5464 }
5465}
5466
5467void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5468 // Cancel previously dispatches pointers.
5469 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5470 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005471 int32_t buttonState = mCurrentRawState.buttonState;
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005472 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5473 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5474 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5475 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5476 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005477 }
5478
5479 // Reset the current pointer gesture.
5480 mPointerGesture.reset();
5481 mPointerVelocityControl.reset();
5482
5483 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005484 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5486 mPointerController->clearSpots();
5487 }
5488}
5489
5490bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5491 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5492 *outCancelPreviousGesture = false;
5493 *outFinishPreviousGesture = false;
5494
5495 // Handle TAP timeout.
5496 if (isTimeout) {
5497#if DEBUG_GESTURES
5498 ALOGD("Gestures: Processing timeout");
5499#endif
5500
5501 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5502 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5503 // The tap/drag timeout has not yet expired.
5504 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5505 + mConfig.pointerGestureTapDragInterval);
5506 } else {
5507 // The tap is finished.
5508#if DEBUG_GESTURES
5509 ALOGD("Gestures: TAP finished");
5510#endif
5511 *outFinishPreviousGesture = true;
5512
5513 mPointerGesture.activeGestureId = -1;
5514 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5515 mPointerGesture.currentGestureIdBits.clear();
5516
5517 mPointerVelocityControl.reset();
5518 return true;
5519 }
5520 }
5521
5522 // We did not handle this timeout.
5523 return false;
5524 }
5525
Michael Wright842500e2015-03-13 17:32:02 -07005526 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5527 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005528
5529 // Update the velocity tracker.
5530 {
5531 VelocityTracker::Position positions[MAX_POINTERS];
5532 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005533 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005535 const RawPointerData::Pointer& pointer =
5536 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005537 positions[count].x = pointer.x * mPointerXMovementScale;
5538 positions[count].y = pointer.y * mPointerYMovementScale;
5539 }
5540 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005541 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 }
5543
5544 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5545 // to NEUTRAL, then we should not generate tap event.
5546 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5547 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5548 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5549 mPointerGesture.resetTap();
5550 }
5551
5552 // Pick a new active touch id if needed.
5553 // Choose an arbitrary pointer that just went down, if there is one.
5554 // Otherwise choose an arbitrary remaining pointer.
5555 // This guarantees we always have an active touch id when there is at least one pointer.
5556 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005557 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5558 int32_t activeTouchId = lastActiveTouchId;
5559 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005560 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005562 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005563 mPointerGesture.firstTouchTime = when;
5564 }
Michael Wright842500e2015-03-13 17:32:02 -07005565 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005566 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005567 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005568 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005569 } else {
5570 activeTouchId = mPointerGesture.activeTouchId = -1;
5571 }
5572 }
5573
5574 // Determine whether we are in quiet time.
5575 bool isQuietTime = false;
5576 if (activeTouchId < 0) {
5577 mPointerGesture.resetQuietTime();
5578 } else {
5579 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5580 if (!isQuietTime) {
5581 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5582 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5583 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5584 && currentFingerCount < 2) {
5585 // Enter quiet time when exiting swipe or freeform state.
5586 // This is to prevent accidentally entering the hover state and flinging the
5587 // pointer when finishing a swipe and there is still one pointer left onscreen.
5588 isQuietTime = true;
5589 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5590 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005591 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005592 // Enter quiet time when releasing the button and there are still two or more
5593 // fingers down. This may indicate that one finger was used to press the button
5594 // but it has not gone up yet.
5595 isQuietTime = true;
5596 }
5597 if (isQuietTime) {
5598 mPointerGesture.quietTime = when;
5599 }
5600 }
5601 }
5602
5603 // Switch states based on button and pointer state.
5604 if (isQuietTime) {
5605 // Case 1: Quiet time. (QUIET)
5606#if DEBUG_GESTURES
5607 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5608 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5609#endif
5610 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5611 *outFinishPreviousGesture = true;
5612 }
5613
5614 mPointerGesture.activeGestureId = -1;
5615 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5616 mPointerGesture.currentGestureIdBits.clear();
5617
5618 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005619 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005620 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5621 // The pointer follows the active touch point.
5622 // Emit DOWN, MOVE, UP events at the pointer location.
5623 //
5624 // Only the active touch matters; other fingers are ignored. This policy helps
5625 // to handle the case where the user places a second finger on the touch pad
5626 // to apply the necessary force to depress an integrated button below the surface.
5627 // We don't want the second finger to be delivered to applications.
5628 //
5629 // For this to work well, we need to make sure to track the pointer that is really
5630 // active. If the user first puts one finger down to click then adds another
5631 // finger to drag then the active pointer should switch to the finger that is
5632 // being dragged.
5633#if DEBUG_GESTURES
5634 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5635 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5636#endif
5637 // Reset state when just starting.
5638 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5639 *outFinishPreviousGesture = true;
5640 mPointerGesture.activeGestureId = 0;
5641 }
5642
5643 // Switch pointers if needed.
5644 // Find the fastest pointer and follow it.
5645 if (activeTouchId >= 0 && currentFingerCount > 1) {
5646 int32_t bestId = -1;
5647 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005648 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005649 uint32_t id = idBits.clearFirstMarkedBit();
5650 float vx, vy;
5651 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5652 float speed = hypotf(vx, vy);
5653 if (speed > bestSpeed) {
5654 bestId = id;
5655 bestSpeed = speed;
5656 }
5657 }
5658 }
5659 if (bestId >= 0 && bestId != activeTouchId) {
5660 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005661#if DEBUG_GESTURES
5662 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5663 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5664#endif
5665 }
5666 }
5667
Jun Mukaifa1706a2015-12-03 01:14:46 -08005668 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005669 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005670 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005671 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005672 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005673 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005674 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5675 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005676
5677 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5678 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5679
5680 // Move the pointer using a relative motion.
5681 // When using spots, the click will occur at the position of the anchor
5682 // spot and all other spots will move there.
5683 mPointerController->move(deltaX, deltaY);
5684 } else {
5685 mPointerVelocityControl.reset();
5686 }
5687
5688 float x, y;
5689 mPointerController->getPosition(&x, &y);
5690
5691 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5692 mPointerGesture.currentGestureIdBits.clear();
5693 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5694 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5695 mPointerGesture.currentGestureProperties[0].clear();
5696 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5697 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5698 mPointerGesture.currentGestureCoords[0].clear();
5699 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5700 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5701 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5702 } else if (currentFingerCount == 0) {
5703 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5704 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5705 *outFinishPreviousGesture = true;
5706 }
5707
5708 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5709 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5710 bool tapped = false;
5711 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5712 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5713 && lastFingerCount == 1) {
5714 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5715 float x, y;
5716 mPointerController->getPosition(&x, &y);
5717 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5718 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5719#if DEBUG_GESTURES
5720 ALOGD("Gestures: TAP");
5721#endif
5722
5723 mPointerGesture.tapUpTime = when;
5724 getContext()->requestTimeoutAtTime(when
5725 + mConfig.pointerGestureTapDragInterval);
5726
5727 mPointerGesture.activeGestureId = 0;
5728 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5729 mPointerGesture.currentGestureIdBits.clear();
5730 mPointerGesture.currentGestureIdBits.markBit(
5731 mPointerGesture.activeGestureId);
5732 mPointerGesture.currentGestureIdToIndex[
5733 mPointerGesture.activeGestureId] = 0;
5734 mPointerGesture.currentGestureProperties[0].clear();
5735 mPointerGesture.currentGestureProperties[0].id =
5736 mPointerGesture.activeGestureId;
5737 mPointerGesture.currentGestureProperties[0].toolType =
5738 AMOTION_EVENT_TOOL_TYPE_FINGER;
5739 mPointerGesture.currentGestureCoords[0].clear();
5740 mPointerGesture.currentGestureCoords[0].setAxisValue(
5741 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5742 mPointerGesture.currentGestureCoords[0].setAxisValue(
5743 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5744 mPointerGesture.currentGestureCoords[0].setAxisValue(
5745 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5746
5747 tapped = true;
5748 } else {
5749#if DEBUG_GESTURES
5750 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5751 x - mPointerGesture.tapX,
5752 y - mPointerGesture.tapY);
5753#endif
5754 }
5755 } else {
5756#if DEBUG_GESTURES
5757 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5758 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5759 (when - mPointerGesture.tapDownTime) * 0.000001f);
5760 } else {
5761 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5762 }
5763#endif
5764 }
5765 }
5766
5767 mPointerVelocityControl.reset();
5768
5769 if (!tapped) {
5770#if DEBUG_GESTURES
5771 ALOGD("Gestures: NEUTRAL");
5772#endif
5773 mPointerGesture.activeGestureId = -1;
5774 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5775 mPointerGesture.currentGestureIdBits.clear();
5776 }
5777 } else if (currentFingerCount == 1) {
5778 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5779 // The pointer follows the active touch point.
5780 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5781 // When in TAP_DRAG, emit MOVE events at the pointer location.
5782 ALOG_ASSERT(activeTouchId >= 0);
5783
5784 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5785 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5786 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5787 float x, y;
5788 mPointerController->getPosition(&x, &y);
5789 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5790 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5791 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5792 } else {
5793#if DEBUG_GESTURES
5794 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5795 x - mPointerGesture.tapX,
5796 y - mPointerGesture.tapY);
5797#endif
5798 }
5799 } else {
5800#if DEBUG_GESTURES
5801 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5802 (when - mPointerGesture.tapUpTime) * 0.000001f);
5803#endif
5804 }
5805 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5806 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5807 }
5808
Jun Mukaifa1706a2015-12-03 01:14:46 -08005809 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005810 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005811 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005812 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005813 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005814 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005815 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5816 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005817
5818 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5819 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5820
5821 // Move the pointer using a relative motion.
5822 // When using spots, the hover or drag will occur at the position of the anchor spot.
5823 mPointerController->move(deltaX, deltaY);
5824 } else {
5825 mPointerVelocityControl.reset();
5826 }
5827
5828 bool down;
5829 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5830#if DEBUG_GESTURES
5831 ALOGD("Gestures: TAP_DRAG");
5832#endif
5833 down = true;
5834 } else {
5835#if DEBUG_GESTURES
5836 ALOGD("Gestures: HOVER");
5837#endif
5838 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5839 *outFinishPreviousGesture = true;
5840 }
5841 mPointerGesture.activeGestureId = 0;
5842 down = false;
5843 }
5844
5845 float x, y;
5846 mPointerController->getPosition(&x, &y);
5847
5848 mPointerGesture.currentGestureIdBits.clear();
5849 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5850 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5851 mPointerGesture.currentGestureProperties[0].clear();
5852 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5853 mPointerGesture.currentGestureProperties[0].toolType =
5854 AMOTION_EVENT_TOOL_TYPE_FINGER;
5855 mPointerGesture.currentGestureCoords[0].clear();
5856 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5857 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5858 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5859 down ? 1.0f : 0.0f);
5860
5861 if (lastFingerCount == 0 && currentFingerCount != 0) {
5862 mPointerGesture.resetTap();
5863 mPointerGesture.tapDownTime = when;
5864 mPointerGesture.tapX = x;
5865 mPointerGesture.tapY = y;
5866 }
5867 } else {
5868 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5869 // We need to provide feedback for each finger that goes down so we cannot wait
5870 // for the fingers to move before deciding what to do.
5871 //
5872 // The ambiguous case is deciding what to do when there are two fingers down but they
5873 // have not moved enough to determine whether they are part of a drag or part of a
5874 // freeform gesture, or just a press or long-press at the pointer location.
5875 //
5876 // When there are two fingers we start with the PRESS hypothesis and we generate a
5877 // down at the pointer location.
5878 //
5879 // When the two fingers move enough or when additional fingers are added, we make
5880 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5881 ALOG_ASSERT(activeTouchId >= 0);
5882
5883 bool settled = when >= mPointerGesture.firstTouchTime
5884 + mConfig.pointerGestureMultitouchSettleInterval;
5885 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5886 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5887 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5888 *outFinishPreviousGesture = true;
5889 } else if (!settled && currentFingerCount > lastFingerCount) {
5890 // Additional pointers have gone down but not yet settled.
5891 // Reset the gesture.
5892#if DEBUG_GESTURES
5893 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5894 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5895 + mConfig.pointerGestureMultitouchSettleInterval - when)
5896 * 0.000001f);
5897#endif
5898 *outCancelPreviousGesture = true;
5899 } else {
5900 // Continue previous gesture.
5901 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5902 }
5903
5904 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5905 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5906 mPointerGesture.activeGestureId = 0;
5907 mPointerGesture.referenceIdBits.clear();
5908 mPointerVelocityControl.reset();
5909
5910 // Use the centroid and pointer location as the reference points for the gesture.
5911#if DEBUG_GESTURES
5912 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5913 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5914 + mConfig.pointerGestureMultitouchSettleInterval - when)
5915 * 0.000001f);
5916#endif
Michael Wright842500e2015-03-13 17:32:02 -07005917 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005918 &mPointerGesture.referenceTouchX,
5919 &mPointerGesture.referenceTouchY);
5920 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5921 &mPointerGesture.referenceGestureY);
5922 }
5923
5924 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005925 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005926 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5927 uint32_t id = idBits.clearFirstMarkedBit();
5928 mPointerGesture.referenceDeltas[id].dx = 0;
5929 mPointerGesture.referenceDeltas[id].dy = 0;
5930 }
Michael Wright842500e2015-03-13 17:32:02 -07005931 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005932
5933 // Add delta for all fingers and calculate a common movement delta.
5934 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005935 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5936 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5938 bool first = (idBits == commonIdBits);
5939 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005940 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5941 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5943 delta.dx += cpd.x - lpd.x;
5944 delta.dy += cpd.y - lpd.y;
5945
5946 if (first) {
5947 commonDeltaX = delta.dx;
5948 commonDeltaY = delta.dy;
5949 } else {
5950 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5951 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5952 }
5953 }
5954
5955 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5956 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5957 float dist[MAX_POINTER_ID + 1];
5958 int32_t distOverThreshold = 0;
5959 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5960 uint32_t id = idBits.clearFirstMarkedBit();
5961 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5962 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5963 delta.dy * mPointerYZoomScale);
5964 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5965 distOverThreshold += 1;
5966 }
5967 }
5968
5969 // Only transition when at least two pointers have moved further than
5970 // the minimum distance threshold.
5971 if (distOverThreshold >= 2) {
5972 if (currentFingerCount > 2) {
5973 // There are more than two pointers, switch to FREEFORM.
5974#if DEBUG_GESTURES
5975 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5976 currentFingerCount);
5977#endif
5978 *outCancelPreviousGesture = true;
5979 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5980 } else {
5981 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005982 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 uint32_t id1 = idBits.clearFirstMarkedBit();
5984 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005985 const RawPointerData::Pointer& p1 =
5986 mCurrentRawState.rawPointerData.pointerForId(id1);
5987 const RawPointerData::Pointer& p2 =
5988 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005989 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5990 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5991 // There are two pointers but they are too far apart for a SWIPE,
5992 // switch to FREEFORM.
5993#if DEBUG_GESTURES
5994 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5995 mutualDistance, mPointerGestureMaxSwipeWidth);
5996#endif
5997 *outCancelPreviousGesture = true;
5998 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5999 } else {
6000 // There are two pointers. Wait for both pointers to start moving
6001 // before deciding whether this is a SWIPE or FREEFORM gesture.
6002 float dist1 = dist[id1];
6003 float dist2 = dist[id2];
6004 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6005 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6006 // Calculate the dot product of the displacement vectors.
6007 // When the vectors are oriented in approximately the same direction,
6008 // the angle betweeen them is near zero and the cosine of the angle
6009 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6010 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6011 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6012 float dx1 = delta1.dx * mPointerXZoomScale;
6013 float dy1 = delta1.dy * mPointerYZoomScale;
6014 float dx2 = delta2.dx * mPointerXZoomScale;
6015 float dy2 = delta2.dy * mPointerYZoomScale;
6016 float dot = dx1 * dx2 + dy1 * dy2;
6017 float cosine = dot / (dist1 * dist2); // denominator always > 0
6018 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6019 // Pointers are moving in the same direction. Switch to SWIPE.
6020#if DEBUG_GESTURES
6021 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6022 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6023 "cosine %0.3f >= %0.3f",
6024 dist1, mConfig.pointerGestureMultitouchMinDistance,
6025 dist2, mConfig.pointerGestureMultitouchMinDistance,
6026 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6027#endif
6028 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6029 } else {
6030 // Pointers are moving in different directions. Switch to FREEFORM.
6031#if DEBUG_GESTURES
6032 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6033 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6034 "cosine %0.3f < %0.3f",
6035 dist1, mConfig.pointerGestureMultitouchMinDistance,
6036 dist2, mConfig.pointerGestureMultitouchMinDistance,
6037 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6038#endif
6039 *outCancelPreviousGesture = true;
6040 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6041 }
6042 }
6043 }
6044 }
6045 }
6046 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6047 // Switch from SWIPE to FREEFORM if additional pointers go down.
6048 // Cancel previous gesture.
6049 if (currentFingerCount > 2) {
6050#if DEBUG_GESTURES
6051 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6052 currentFingerCount);
6053#endif
6054 *outCancelPreviousGesture = true;
6055 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6056 }
6057 }
6058
6059 // Move the reference points based on the overall group motion of the fingers
6060 // except in PRESS mode while waiting for a transition to occur.
6061 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6062 && (commonDeltaX || commonDeltaY)) {
6063 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6064 uint32_t id = idBits.clearFirstMarkedBit();
6065 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6066 delta.dx = 0;
6067 delta.dy = 0;
6068 }
6069
6070 mPointerGesture.referenceTouchX += commonDeltaX;
6071 mPointerGesture.referenceTouchY += commonDeltaY;
6072
6073 commonDeltaX *= mPointerXMovementScale;
6074 commonDeltaY *= mPointerYMovementScale;
6075
6076 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6077 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6078
6079 mPointerGesture.referenceGestureX += commonDeltaX;
6080 mPointerGesture.referenceGestureY += commonDeltaY;
6081 }
6082
6083 // Report gestures.
6084 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6085 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6086 // PRESS or SWIPE mode.
6087#if DEBUG_GESTURES
6088 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6089 "activeGestureId=%d, currentTouchPointerCount=%d",
6090 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6091#endif
6092 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6093
6094 mPointerGesture.currentGestureIdBits.clear();
6095 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6096 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6097 mPointerGesture.currentGestureProperties[0].clear();
6098 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6099 mPointerGesture.currentGestureProperties[0].toolType =
6100 AMOTION_EVENT_TOOL_TYPE_FINGER;
6101 mPointerGesture.currentGestureCoords[0].clear();
6102 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6103 mPointerGesture.referenceGestureX);
6104 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6105 mPointerGesture.referenceGestureY);
6106 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6107 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6108 // FREEFORM mode.
6109#if DEBUG_GESTURES
6110 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6111 "activeGestureId=%d, currentTouchPointerCount=%d",
6112 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6113#endif
6114 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6115
6116 mPointerGesture.currentGestureIdBits.clear();
6117
6118 BitSet32 mappedTouchIdBits;
6119 BitSet32 usedGestureIdBits;
6120 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6121 // Initially, assign the active gesture id to the active touch point
6122 // if there is one. No other touch id bits are mapped yet.
6123 if (!*outCancelPreviousGesture) {
6124 mappedTouchIdBits.markBit(activeTouchId);
6125 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6126 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6127 mPointerGesture.activeGestureId;
6128 } else {
6129 mPointerGesture.activeGestureId = -1;
6130 }
6131 } else {
6132 // Otherwise, assume we mapped all touches from the previous frame.
6133 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006134 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6135 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6137
6138 // Check whether we need to choose a new active gesture id because the
6139 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006140 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6141 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006142 !upTouchIdBits.isEmpty(); ) {
6143 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6144 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6145 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6146 mPointerGesture.activeGestureId = -1;
6147 break;
6148 }
6149 }
6150 }
6151
6152#if DEBUG_GESTURES
6153 ALOGD("Gestures: FREEFORM follow up "
6154 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6155 "activeGestureId=%d",
6156 mappedTouchIdBits.value, usedGestureIdBits.value,
6157 mPointerGesture.activeGestureId);
6158#endif
6159
Michael Wright842500e2015-03-13 17:32:02 -07006160 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 for (uint32_t i = 0; i < currentFingerCount; i++) {
6162 uint32_t touchId = idBits.clearFirstMarkedBit();
6163 uint32_t gestureId;
6164 if (!mappedTouchIdBits.hasBit(touchId)) {
6165 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6166 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6167#if DEBUG_GESTURES
6168 ALOGD("Gestures: FREEFORM "
6169 "new mapping for touch id %d -> gesture id %d",
6170 touchId, gestureId);
6171#endif
6172 } else {
6173 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6174#if DEBUG_GESTURES
6175 ALOGD("Gestures: FREEFORM "
6176 "existing mapping for touch id %d -> gesture id %d",
6177 touchId, gestureId);
6178#endif
6179 }
6180 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6181 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6182
6183 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006184 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6186 * mPointerXZoomScale;
6187 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6188 * mPointerYZoomScale;
6189 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6190
6191 mPointerGesture.currentGestureProperties[i].clear();
6192 mPointerGesture.currentGestureProperties[i].id = gestureId;
6193 mPointerGesture.currentGestureProperties[i].toolType =
6194 AMOTION_EVENT_TOOL_TYPE_FINGER;
6195 mPointerGesture.currentGestureCoords[i].clear();
6196 mPointerGesture.currentGestureCoords[i].setAxisValue(
6197 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6198 mPointerGesture.currentGestureCoords[i].setAxisValue(
6199 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6200 mPointerGesture.currentGestureCoords[i].setAxisValue(
6201 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6202 }
6203
6204 if (mPointerGesture.activeGestureId < 0) {
6205 mPointerGesture.activeGestureId =
6206 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6207#if DEBUG_GESTURES
6208 ALOGD("Gestures: FREEFORM new "
6209 "activeGestureId=%d", mPointerGesture.activeGestureId);
6210#endif
6211 }
6212 }
6213 }
6214
Michael Wright842500e2015-03-13 17:32:02 -07006215 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216
6217#if DEBUG_GESTURES
6218 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6219 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6220 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6221 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6222 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6223 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6224 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6225 uint32_t id = idBits.clearFirstMarkedBit();
6226 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6227 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6228 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6229 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6230 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6231 id, index, properties.toolType,
6232 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6233 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6234 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6235 }
6236 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6237 uint32_t id = idBits.clearFirstMarkedBit();
6238 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6239 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6240 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6241 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6242 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6243 id, index, properties.toolType,
6244 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6245 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6246 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6247 }
6248#endif
6249 return true;
6250}
6251
6252void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6253 mPointerSimple.currentCoords.clear();
6254 mPointerSimple.currentProperties.clear();
6255
6256 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006257 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6258 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6259 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6260 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6261 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 mPointerController->setPosition(x, y);
6263
Michael Wright842500e2015-03-13 17:32:02 -07006264 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 down = !hovering;
6266
6267 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006268 mPointerSimple.currentCoords.copyFrom(
6269 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6271 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6272 mPointerSimple.currentProperties.id = 0;
6273 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006274 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275 } else {
6276 down = false;
6277 hovering = false;
6278 }
6279
6280 dispatchPointerSimple(when, policyFlags, down, hovering);
6281}
6282
6283void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6284 abortPointerSimple(when, policyFlags);
6285}
6286
6287void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6288 mPointerSimple.currentCoords.clear();
6289 mPointerSimple.currentProperties.clear();
6290
6291 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006292 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6293 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6294 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006295 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006296 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6297 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006298 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006299 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006301 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006302 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303 * mPointerYMovementScale;
6304
6305 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6306 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6307
6308 mPointerController->move(deltaX, deltaY);
6309 } else {
6310 mPointerVelocityControl.reset();
6311 }
6312
Michael Wright842500e2015-03-13 17:32:02 -07006313 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 hovering = !down;
6315
6316 float x, y;
6317 mPointerController->getPosition(&x, &y);
6318 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006319 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006320 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6321 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6322 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6323 hovering ? 0.0f : 1.0f);
6324 mPointerSimple.currentProperties.id = 0;
6325 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006326 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006327 } else {
6328 mPointerVelocityControl.reset();
6329
6330 down = false;
6331 hovering = false;
6332 }
6333
6334 dispatchPointerSimple(when, policyFlags, down, hovering);
6335}
6336
6337void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6338 abortPointerSimple(when, policyFlags);
6339
6340 mPointerVelocityControl.reset();
6341}
6342
6343void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6344 bool down, bool hovering) {
6345 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006346 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347
Garfield Tan00f511d2019-06-12 16:55:40 -07006348 if (down || hovering) {
6349 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6350 mPointerController->clearSpots();
6351 mPointerController->setButtonState(mCurrentRawState.buttonState);
6352 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6353 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6354 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006355 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006356 displayId = mPointerController->getDisplayId();
6357
6358 float xCursorPosition;
6359 float yCursorPosition;
6360 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361
6362 if (mPointerSimple.down && !down) {
6363 mPointerSimple.down = false;
6364
6365 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006366 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6367 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6368 mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006369 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6370 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6371 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6372 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 getListener()->notifyMotion(&args);
6374 }
6375
6376 if (mPointerSimple.hovering && !hovering) {
6377 mPointerSimple.hovering = false;
6378
6379 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006380 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6381 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6382 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006383 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6384 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6385 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6386 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 getListener()->notifyMotion(&args);
6388 }
6389
6390 if (down) {
6391 if (!mPointerSimple.down) {
6392 mPointerSimple.down = true;
6393 mPointerSimple.downTime = when;
6394
6395 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006396 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6397 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6398 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006399 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6400 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6401 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6402 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006403 getListener()->notifyMotion(&args);
6404 }
6405
6406 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006407 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6408 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6409 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006410 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6411 &mPointerSimple.currentCoords, mOrientedXPrecision,
6412 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6413 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006414 getListener()->notifyMotion(&args);
6415 }
6416
6417 if (hovering) {
6418 if (!mPointerSimple.hovering) {
6419 mPointerSimple.hovering = true;
6420
6421 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006422 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6423 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6424 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006425 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6426 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6427 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6428 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006429 getListener()->notifyMotion(&args);
6430 }
6431
6432 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006433 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6434 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6435 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006436 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6437 &mPointerSimple.currentCoords, mOrientedXPrecision,
6438 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6439 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006440 getListener()->notifyMotion(&args);
6441 }
6442
Michael Wright842500e2015-03-13 17:32:02 -07006443 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6444 float vscroll = mCurrentRawState.rawVScroll;
6445 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006446 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6447 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006448
6449 // Send scroll.
6450 PointerCoords pointerCoords;
6451 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6452 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6453 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6454
Garfield Tan00f511d2019-06-12 16:55:40 -07006455 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6456 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6457 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006458 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6459 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
6460 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6461 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006462 getListener()->notifyMotion(&args);
6463 }
6464
6465 // Save state.
6466 if (down || hovering) {
6467 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6468 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6469 } else {
6470 mPointerSimple.reset();
6471 }
6472}
6473
6474void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6475 mPointerSimple.currentCoords.clear();
6476 mPointerSimple.currentProperties.clear();
6477
6478 dispatchPointerSimple(when, policyFlags, false, false);
6479}
6480
6481void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006482 int32_t action, int32_t actionButton, int32_t flags,
6483 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6484 const PointerProperties* properties,
6485 const PointerCoords* coords, const uint32_t* idToIndex,
6486 BitSet32 idBits, int32_t changedId, float xPrecision,
6487 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488 PointerCoords pointerCoords[MAX_POINTERS];
6489 PointerProperties pointerProperties[MAX_POINTERS];
6490 uint32_t pointerCount = 0;
6491 while (!idBits.isEmpty()) {
6492 uint32_t id = idBits.clearFirstMarkedBit();
6493 uint32_t index = idToIndex[id];
6494 pointerProperties[pointerCount].copyFrom(properties[index]);
6495 pointerCoords[pointerCount].copyFrom(coords[index]);
6496
6497 if (changedId >= 0 && id == uint32_t(changedId)) {
6498 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6499 }
6500
6501 pointerCount += 1;
6502 }
6503
6504 ALOG_ASSERT(pointerCount != 0);
6505
6506 if (changedId >= 0 && pointerCount == 1) {
6507 // Replace initial down and final up action.
6508 // We can compare the action without masking off the changed pointer index
6509 // because we know the index is 0.
6510 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6511 action = AMOTION_EVENT_ACTION_DOWN;
6512 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6513 action = AMOTION_EVENT_ACTION_UP;
6514 } else {
6515 // Can't happen.
6516 ALOG_ASSERT(false);
6517 }
6518 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006519 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6520 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6521 if (mDeviceMode == DEVICE_MODE_POINTER) {
6522 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6523 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006524 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006525 const int32_t deviceId = getDeviceId();
6526 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006527 std::for_each(frames.begin(), frames.end(),
6528 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006529 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6530 policyFlags, action, actionButton, flags, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006531 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
6532 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
6533 downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534 getListener()->notifyMotion(&args);
6535}
6536
6537bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6538 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6539 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6540 BitSet32 idBits) const {
6541 bool changed = false;
6542 while (!idBits.isEmpty()) {
6543 uint32_t id = idBits.clearFirstMarkedBit();
6544 uint32_t inIndex = inIdToIndex[id];
6545 uint32_t outIndex = outIdToIndex[id];
6546
6547 const PointerProperties& curInProperties = inProperties[inIndex];
6548 const PointerCoords& curInCoords = inCoords[inIndex];
6549 PointerProperties& curOutProperties = outProperties[outIndex];
6550 PointerCoords& curOutCoords = outCoords[outIndex];
6551
6552 if (curInProperties != curOutProperties) {
6553 curOutProperties.copyFrom(curInProperties);
6554 changed = true;
6555 }
6556
6557 if (curInCoords != curOutCoords) {
6558 curOutCoords.copyFrom(curInCoords);
6559 changed = true;
6560 }
6561 }
6562 return changed;
6563}
6564
6565void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006566 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6568 }
6569}
6570
Jeff Brownc9aa6282015-02-11 19:03:28 -08006571void TouchInputMapper::cancelTouch(nsecs_t when) {
6572 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006573 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006574}
6575
Michael Wrightd02c5b62014-02-10 15:10:22 -08006576bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006577 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006578 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006580 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6581 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6582 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006583}
6584
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006585const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006587 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588#if DEBUG_VIRTUAL_KEYS
6589 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6590 "left=%d, top=%d, right=%d, bottom=%d",
6591 x, y,
6592 virtualKey.keyCode, virtualKey.scanCode,
6593 virtualKey.hitLeft, virtualKey.hitTop,
6594 virtualKey.hitRight, virtualKey.hitBottom);
6595#endif
6596
6597 if (virtualKey.isHit(x, y)) {
6598 return & virtualKey;
6599 }
6600 }
6601
Yi Kong9b14ac62018-07-17 13:48:38 -07006602 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603}
6604
Michael Wright842500e2015-03-13 17:32:02 -07006605void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6606 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6607 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608
Michael Wright842500e2015-03-13 17:32:02 -07006609 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006610
6611 if (currentPointerCount == 0) {
6612 // No pointers to assign.
6613 return;
6614 }
6615
6616 if (lastPointerCount == 0) {
6617 // All pointers are new.
6618 for (uint32_t i = 0; i < currentPointerCount; i++) {
6619 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006620 current->rawPointerData.pointers[i].id = id;
6621 current->rawPointerData.idToIndex[id] = i;
6622 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006623 }
6624 return;
6625 }
6626
6627 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006628 && current->rawPointerData.pointers[0].toolType
6629 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006631 uint32_t id = last->rawPointerData.pointers[0].id;
6632 current->rawPointerData.pointers[0].id = id;
6633 current->rawPointerData.idToIndex[id] = 0;
6634 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635 return;
6636 }
6637
6638 // General case.
6639 // We build a heap of squared euclidean distances between current and last pointers
6640 // associated with the current and last pointer indices. Then, we find the best
6641 // match (by distance) for each current pointer.
6642 // The pointers must have the same tool type but it is possible for them to
6643 // transition from hovering to touching or vice-versa while retaining the same id.
6644 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6645
6646 uint32_t heapSize = 0;
6647 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6648 currentPointerIndex++) {
6649 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6650 lastPointerIndex++) {
6651 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006652 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006653 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006654 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006655 if (currentPointer.toolType == lastPointer.toolType) {
6656 int64_t deltaX = currentPointer.x - lastPointer.x;
6657 int64_t deltaY = currentPointer.y - lastPointer.y;
6658
6659 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6660
6661 // Insert new element into the heap (sift up).
6662 heap[heapSize].currentPointerIndex = currentPointerIndex;
6663 heap[heapSize].lastPointerIndex = lastPointerIndex;
6664 heap[heapSize].distance = distance;
6665 heapSize += 1;
6666 }
6667 }
6668 }
6669
6670 // Heapify
6671 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6672 startIndex -= 1;
6673 for (uint32_t parentIndex = startIndex; ;) {
6674 uint32_t childIndex = parentIndex * 2 + 1;
6675 if (childIndex >= heapSize) {
6676 break;
6677 }
6678
6679 if (childIndex + 1 < heapSize
6680 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6681 childIndex += 1;
6682 }
6683
6684 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6685 break;
6686 }
6687
6688 swap(heap[parentIndex], heap[childIndex]);
6689 parentIndex = childIndex;
6690 }
6691 }
6692
6693#if DEBUG_POINTER_ASSIGNMENT
6694 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6695 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006696 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006697 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6698 heap[i].distance);
6699 }
6700#endif
6701
6702 // Pull matches out by increasing order of distance.
6703 // To avoid reassigning pointers that have already been matched, the loop keeps track
6704 // of which last and current pointers have been matched using the matchedXXXBits variables.
6705 // It also tracks the used pointer id bits.
6706 BitSet32 matchedLastBits(0);
6707 BitSet32 matchedCurrentBits(0);
6708 BitSet32 usedIdBits(0);
6709 bool first = true;
6710 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6711 while (heapSize > 0) {
6712 if (first) {
6713 // The first time through the loop, we just consume the root element of
6714 // the heap (the one with smallest distance).
6715 first = false;
6716 } else {
6717 // Previous iterations consumed the root element of the heap.
6718 // Pop root element off of the heap (sift down).
6719 heap[0] = heap[heapSize];
6720 for (uint32_t parentIndex = 0; ;) {
6721 uint32_t childIndex = parentIndex * 2 + 1;
6722 if (childIndex >= heapSize) {
6723 break;
6724 }
6725
6726 if (childIndex + 1 < heapSize
6727 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6728 childIndex += 1;
6729 }
6730
6731 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6732 break;
6733 }
6734
6735 swap(heap[parentIndex], heap[childIndex]);
6736 parentIndex = childIndex;
6737 }
6738
6739#if DEBUG_POINTER_ASSIGNMENT
6740 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6741 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006742 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006743 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6744 heap[i].distance);
6745 }
6746#endif
6747 }
6748
6749 heapSize -= 1;
6750
6751 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6752 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6753
6754 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6755 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6756
6757 matchedCurrentBits.markBit(currentPointerIndex);
6758 matchedLastBits.markBit(lastPointerIndex);
6759
Michael Wright842500e2015-03-13 17:32:02 -07006760 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6761 current->rawPointerData.pointers[currentPointerIndex].id = id;
6762 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6763 current->rawPointerData.markIdBit(id,
6764 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006765 usedIdBits.markBit(id);
6766
6767#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006768 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6769 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006770 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6771#endif
6772 break;
6773 }
6774 }
6775
6776 // Assign fresh ids to pointers that were not matched in the process.
6777 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6778 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6779 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6780
Michael Wright842500e2015-03-13 17:32:02 -07006781 current->rawPointerData.pointers[currentPointerIndex].id = id;
6782 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6783 current->rawPointerData.markIdBit(id,
6784 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006785
6786#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006787 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006788#endif
6789 }
6790}
6791
6792int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6793 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6794 return AKEY_STATE_VIRTUAL;
6795 }
6796
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006797 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006798 if (virtualKey.keyCode == keyCode) {
6799 return AKEY_STATE_UP;
6800 }
6801 }
6802
6803 return AKEY_STATE_UNKNOWN;
6804}
6805
6806int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6807 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6808 return AKEY_STATE_VIRTUAL;
6809 }
6810
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006811 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006812 if (virtualKey.scanCode == scanCode) {
6813 return AKEY_STATE_UP;
6814 }
6815 }
6816
6817 return AKEY_STATE_UNKNOWN;
6818}
6819
6820bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6821 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006822 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006823 for (size_t i = 0; i < numCodes; i++) {
6824 if (virtualKey.keyCode == keyCodes[i]) {
6825 outFlags[i] = 1;
6826 }
6827 }
6828 }
6829
6830 return true;
6831}
6832
Arthur Hungc23540e2018-11-29 20:42:11 +08006833std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6834 if (mParameters.hasAssociatedDisplay) {
6835 if (mDeviceMode == DEVICE_MODE_POINTER) {
6836 return std::make_optional(mPointerController->getDisplayId());
6837 } else {
6838 return std::make_optional(mViewport.displayId);
6839 }
6840 }
6841 return std::nullopt;
6842}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006843
6844// --- SingleTouchInputMapper ---
6845
6846SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6847 TouchInputMapper(device) {
6848}
6849
6850SingleTouchInputMapper::~SingleTouchInputMapper() {
6851}
6852
6853void SingleTouchInputMapper::reset(nsecs_t when) {
6854 mSingleTouchMotionAccumulator.reset(getDevice());
6855
6856 TouchInputMapper::reset(when);
6857}
6858
6859void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6860 TouchInputMapper::process(rawEvent);
6861
6862 mSingleTouchMotionAccumulator.process(rawEvent);
6863}
6864
Michael Wright842500e2015-03-13 17:32:02 -07006865void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006866 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006867 outState->rawPointerData.pointerCount = 1;
6868 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006869
6870 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6871 && (mTouchButtonAccumulator.isHovering()
6872 || (mRawPointerAxes.pressure.valid
6873 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006874 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006875
Michael Wright842500e2015-03-13 17:32:02 -07006876 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006877 outPointer.id = 0;
6878 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6879 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6880 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6881 outPointer.touchMajor = 0;
6882 outPointer.touchMinor = 0;
6883 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6884 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6885 outPointer.orientation = 0;
6886 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6887 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6888 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6889 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6890 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6891 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6892 }
6893 outPointer.isHovering = isHovering;
6894 }
6895}
6896
6897void SingleTouchInputMapper::configureRawPointerAxes() {
6898 TouchInputMapper::configureRawPointerAxes();
6899
6900 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6901 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6902 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6903 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6904 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6905 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6906 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6907}
6908
6909bool SingleTouchInputMapper::hasStylus() const {
6910 return mTouchButtonAccumulator.hasStylus();
6911}
6912
6913
6914// --- MultiTouchInputMapper ---
6915
6916MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6917 TouchInputMapper(device) {
6918}
6919
6920MultiTouchInputMapper::~MultiTouchInputMapper() {
6921}
6922
6923void MultiTouchInputMapper::reset(nsecs_t when) {
6924 mMultiTouchMotionAccumulator.reset(getDevice());
6925
6926 mPointerIdBits.clear();
6927
6928 TouchInputMapper::reset(when);
6929}
6930
6931void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6932 TouchInputMapper::process(rawEvent);
6933
6934 mMultiTouchMotionAccumulator.process(rawEvent);
6935}
6936
Michael Wright842500e2015-03-13 17:32:02 -07006937void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006938 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6939 size_t outCount = 0;
6940 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006941 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006942
6943 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6944 const MultiTouchMotionAccumulator::Slot* inSlot =
6945 mMultiTouchMotionAccumulator.getSlot(inIndex);
6946 if (!inSlot->isInUse()) {
6947 continue;
6948 }
6949
6950 if (outCount >= MAX_POINTERS) {
6951#if DEBUG_POINTERS
6952 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6953 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006954 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006955#endif
6956 break; // too many fingers!
6957 }
6958
Michael Wright842500e2015-03-13 17:32:02 -07006959 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006960 outPointer.x = inSlot->getX();
6961 outPointer.y = inSlot->getY();
6962 outPointer.pressure = inSlot->getPressure();
6963 outPointer.touchMajor = inSlot->getTouchMajor();
6964 outPointer.touchMinor = inSlot->getTouchMinor();
6965 outPointer.toolMajor = inSlot->getToolMajor();
6966 outPointer.toolMinor = inSlot->getToolMinor();
6967 outPointer.orientation = inSlot->getOrientation();
6968 outPointer.distance = inSlot->getDistance();
6969 outPointer.tiltX = 0;
6970 outPointer.tiltY = 0;
6971
6972 outPointer.toolType = inSlot->getToolType();
6973 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6974 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6975 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6976 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6977 }
6978 }
6979
6980 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6981 && (mTouchButtonAccumulator.isHovering()
6982 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6983 outPointer.isHovering = isHovering;
6984
6985 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006986 if (mHavePointerIds) {
6987 int32_t trackingId = inSlot->getTrackingId();
6988 int32_t id = -1;
6989 if (trackingId >= 0) {
6990 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6991 uint32_t n = idBits.clearFirstMarkedBit();
6992 if (mPointerTrackingIdMap[n] == trackingId) {
6993 id = n;
6994 }
6995 }
6996
6997 if (id < 0 && !mPointerIdBits.isFull()) {
6998 id = mPointerIdBits.markFirstUnmarkedBit();
6999 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007000 }
Michael Wright842500e2015-03-13 17:32:02 -07007001 }
gaoshang1a632de2016-08-24 10:23:50 +08007002 if (id < 0) {
7003 mHavePointerIds = false;
7004 outState->rawPointerData.clearIdBits();
7005 newPointerIdBits.clear();
7006 } else {
7007 outPointer.id = id;
7008 outState->rawPointerData.idToIndex[id] = outCount;
7009 outState->rawPointerData.markIdBit(id, isHovering);
7010 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007011 }
Michael Wright842500e2015-03-13 17:32:02 -07007012 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007013 outCount += 1;
7014 }
7015
Michael Wright842500e2015-03-13 17:32:02 -07007016 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007017 mPointerIdBits = newPointerIdBits;
7018
7019 mMultiTouchMotionAccumulator.finishSync();
7020}
7021
7022void MultiTouchInputMapper::configureRawPointerAxes() {
7023 TouchInputMapper::configureRawPointerAxes();
7024
7025 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7026 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7027 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7028 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7029 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7030 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7031 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7032 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7033 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7034 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7035 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7036
7037 if (mRawPointerAxes.trackingId.valid
7038 && mRawPointerAxes.slot.valid
7039 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7040 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7041 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007042 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7043 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007044 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007045 slotCount = MAX_SLOTS;
7046 }
7047 mMultiTouchMotionAccumulator.configure(getDevice(),
7048 slotCount, true /*usingSlotsProtocol*/);
7049 } else {
7050 mMultiTouchMotionAccumulator.configure(getDevice(),
7051 MAX_POINTERS, false /*usingSlotsProtocol*/);
7052 }
7053}
7054
7055bool MultiTouchInputMapper::hasStylus() const {
7056 return mMultiTouchMotionAccumulator.hasStylus()
7057 || mTouchButtonAccumulator.hasStylus();
7058}
7059
Michael Wright842500e2015-03-13 17:32:02 -07007060// --- ExternalStylusInputMapper
7061
7062ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7063 InputMapper(device) {
7064
7065}
7066
7067uint32_t ExternalStylusInputMapper::getSources() {
7068 return AINPUT_SOURCE_STYLUS;
7069}
7070
7071void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7072 InputMapper::populateDeviceInfo(info);
7073 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7074 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7075}
7076
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007077void ExternalStylusInputMapper::dump(std::string& dump) {
7078 dump += INDENT2 "External Stylus Input Mapper:\n";
7079 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007080 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007081 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007082 dumpStylusState(dump, mStylusState);
7083}
7084
7085void ExternalStylusInputMapper::configure(nsecs_t when,
7086 const InputReaderConfiguration* config, uint32_t changes) {
7087 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7088 mTouchButtonAccumulator.configure(getDevice());
7089}
7090
7091void ExternalStylusInputMapper::reset(nsecs_t when) {
7092 InputDevice* device = getDevice();
7093 mSingleTouchMotionAccumulator.reset(device);
7094 mTouchButtonAccumulator.reset(device);
7095 InputMapper::reset(when);
7096}
7097
7098void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7099 mSingleTouchMotionAccumulator.process(rawEvent);
7100 mTouchButtonAccumulator.process(rawEvent);
7101
7102 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7103 sync(rawEvent->when);
7104 }
7105}
7106
7107void ExternalStylusInputMapper::sync(nsecs_t when) {
7108 mStylusState.clear();
7109
7110 mStylusState.when = when;
7111
Michael Wright45ccacf2015-04-21 19:01:58 +01007112 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7113 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7114 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7115 }
7116
Michael Wright842500e2015-03-13 17:32:02 -07007117 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7118 if (mRawPressureAxis.valid) {
7119 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7120 } else if (mTouchButtonAccumulator.isToolActive()) {
7121 mStylusState.pressure = 1.0f;
7122 } else {
7123 mStylusState.pressure = 0.0f;
7124 }
7125
7126 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007127
7128 mContext->dispatchExternalStylusState(mStylusState);
7129}
7130
Michael Wrightd02c5b62014-02-10 15:10:22 -08007131
7132// --- JoystickInputMapper ---
7133
7134JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7135 InputMapper(device) {
7136}
7137
7138JoystickInputMapper::~JoystickInputMapper() {
7139}
7140
7141uint32_t JoystickInputMapper::getSources() {
7142 return AINPUT_SOURCE_JOYSTICK;
7143}
7144
7145void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7146 InputMapper::populateDeviceInfo(info);
7147
7148 for (size_t i = 0; i < mAxes.size(); i++) {
7149 const Axis& axis = mAxes.valueAt(i);
7150 addMotionRange(axis.axisInfo.axis, axis, info);
7151
7152 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7153 addMotionRange(axis.axisInfo.highAxis, axis, info);
7154
7155 }
7156 }
7157}
7158
7159void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7160 InputDeviceInfo* info) {
7161 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7162 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7163 /* In order to ease the transition for developers from using the old axes
7164 * to the newer, more semantically correct axes, we'll continue to register
7165 * the old axes as duplicates of their corresponding new ones. */
7166 int32_t compatAxis = getCompatAxis(axisId);
7167 if (compatAxis >= 0) {
7168 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7169 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7170 }
7171}
7172
7173/* A mapping from axes the joystick actually has to the axes that should be
7174 * artificially created for compatibility purposes.
7175 * Returns -1 if no compatibility axis is needed. */
7176int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7177 switch(axis) {
7178 case AMOTION_EVENT_AXIS_LTRIGGER:
7179 return AMOTION_EVENT_AXIS_BRAKE;
7180 case AMOTION_EVENT_AXIS_RTRIGGER:
7181 return AMOTION_EVENT_AXIS_GAS;
7182 }
7183 return -1;
7184}
7185
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007186void JoystickInputMapper::dump(std::string& dump) {
7187 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007188
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007189 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007190 size_t numAxes = mAxes.size();
7191 for (size_t i = 0; i < numAxes; i++) {
7192 const Axis& axis = mAxes.valueAt(i);
7193 const char* label = getAxisLabel(axis.axisInfo.axis);
7194 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007195 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007196 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007197 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007198 }
7199 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7200 label = getAxisLabel(axis.axisInfo.highAxis);
7201 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007202 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007203 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007204 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007205 axis.axisInfo.splitValue);
7206 }
7207 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007208 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007209 }
7210
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007211 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 -08007212 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007213 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007214 "highScale=%0.5f, highOffset=%0.5f\n",
7215 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007216 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007217 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7218 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7219 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7220 }
7221}
7222
7223void JoystickInputMapper::configure(nsecs_t when,
7224 const InputReaderConfiguration* config, uint32_t changes) {
7225 InputMapper::configure(when, config, changes);
7226
7227 if (!changes) { // first time only
7228 // Collect all axes.
7229 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7230 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7231 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7232 continue; // axis must be claimed by a different device
7233 }
7234
7235 RawAbsoluteAxisInfo rawAxisInfo;
7236 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7237 if (rawAxisInfo.valid) {
7238 // Map axis.
7239 AxisInfo axisInfo;
7240 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7241 if (!explicitlyMapped) {
7242 // Axis is not explicitly mapped, will choose a generic axis later.
7243 axisInfo.mode = AxisInfo::MODE_NORMAL;
7244 axisInfo.axis = -1;
7245 }
7246
7247 // Apply flat override.
7248 int32_t rawFlat = axisInfo.flatOverride < 0
7249 ? rawAxisInfo.flat : axisInfo.flatOverride;
7250
7251 // Calculate scaling factors and limits.
7252 Axis axis;
7253 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7254 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7255 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7256 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7257 scale, 0.0f, highScale, 0.0f,
7258 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7259 rawAxisInfo.resolution * scale);
7260 } else if (isCenteredAxis(axisInfo.axis)) {
7261 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7262 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7263 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7264 scale, offset, scale, offset,
7265 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7266 rawAxisInfo.resolution * scale);
7267 } else {
7268 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7269 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7270 scale, 0.0f, scale, 0.0f,
7271 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7272 rawAxisInfo.resolution * scale);
7273 }
7274
7275 // To eliminate noise while the joystick is at rest, filter out small variations
7276 // in axis values up front.
7277 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7278
7279 mAxes.add(abs, axis);
7280 }
7281 }
7282
7283 // If there are too many axes, start dropping them.
7284 // Prefer to keep explicitly mapped axes.
7285 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007286 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007287 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007288 pruneAxes(true);
7289 pruneAxes(false);
7290 }
7291
7292 // Assign generic axis ids to remaining axes.
7293 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7294 size_t numAxes = mAxes.size();
7295 for (size_t i = 0; i < numAxes; i++) {
7296 Axis& axis = mAxes.editValueAt(i);
7297 if (axis.axisInfo.axis < 0) {
7298 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7299 && haveAxis(nextGenericAxisId)) {
7300 nextGenericAxisId += 1;
7301 }
7302
7303 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7304 axis.axisInfo.axis = nextGenericAxisId;
7305 nextGenericAxisId += 1;
7306 } else {
7307 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7308 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007309 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007310 mAxes.removeItemsAt(i--);
7311 numAxes -= 1;
7312 }
7313 }
7314 }
7315 }
7316}
7317
7318bool JoystickInputMapper::haveAxis(int32_t axisId) {
7319 size_t numAxes = mAxes.size();
7320 for (size_t i = 0; i < numAxes; i++) {
7321 const Axis& axis = mAxes.valueAt(i);
7322 if (axis.axisInfo.axis == axisId
7323 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7324 && axis.axisInfo.highAxis == axisId)) {
7325 return true;
7326 }
7327 }
7328 return false;
7329}
7330
7331void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7332 size_t i = mAxes.size();
7333 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7334 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7335 continue;
7336 }
7337 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007338 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007339 mAxes.removeItemsAt(i);
7340 }
7341}
7342
7343bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7344 switch (axis) {
7345 case AMOTION_EVENT_AXIS_X:
7346 case AMOTION_EVENT_AXIS_Y:
7347 case AMOTION_EVENT_AXIS_Z:
7348 case AMOTION_EVENT_AXIS_RX:
7349 case AMOTION_EVENT_AXIS_RY:
7350 case AMOTION_EVENT_AXIS_RZ:
7351 case AMOTION_EVENT_AXIS_HAT_X:
7352 case AMOTION_EVENT_AXIS_HAT_Y:
7353 case AMOTION_EVENT_AXIS_ORIENTATION:
7354 case AMOTION_EVENT_AXIS_RUDDER:
7355 case AMOTION_EVENT_AXIS_WHEEL:
7356 return true;
7357 default:
7358 return false;
7359 }
7360}
7361
7362void JoystickInputMapper::reset(nsecs_t when) {
7363 // Recenter all axes.
7364 size_t numAxes = mAxes.size();
7365 for (size_t i = 0; i < numAxes; i++) {
7366 Axis& axis = mAxes.editValueAt(i);
7367 axis.resetValue();
7368 }
7369
7370 InputMapper::reset(when);
7371}
7372
7373void JoystickInputMapper::process(const RawEvent* rawEvent) {
7374 switch (rawEvent->type) {
7375 case EV_ABS: {
7376 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7377 if (index >= 0) {
7378 Axis& axis = mAxes.editValueAt(index);
7379 float newValue, highNewValue;
7380 switch (axis.axisInfo.mode) {
7381 case AxisInfo::MODE_INVERT:
7382 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7383 * axis.scale + axis.offset;
7384 highNewValue = 0.0f;
7385 break;
7386 case AxisInfo::MODE_SPLIT:
7387 if (rawEvent->value < axis.axisInfo.splitValue) {
7388 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7389 * axis.scale + axis.offset;
7390 highNewValue = 0.0f;
7391 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7392 newValue = 0.0f;
7393 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7394 * axis.highScale + axis.highOffset;
7395 } else {
7396 newValue = 0.0f;
7397 highNewValue = 0.0f;
7398 }
7399 break;
7400 default:
7401 newValue = rawEvent->value * axis.scale + axis.offset;
7402 highNewValue = 0.0f;
7403 break;
7404 }
7405 axis.newValue = newValue;
7406 axis.highNewValue = highNewValue;
7407 }
7408 break;
7409 }
7410
7411 case EV_SYN:
7412 switch (rawEvent->code) {
7413 case SYN_REPORT:
7414 sync(rawEvent->when, false /*force*/);
7415 break;
7416 }
7417 break;
7418 }
7419}
7420
7421void JoystickInputMapper::sync(nsecs_t when, bool force) {
7422 if (!filterAxes(force)) {
7423 return;
7424 }
7425
7426 int32_t metaState = mContext->getGlobalMetaState();
7427 int32_t buttonState = 0;
7428
7429 PointerProperties pointerProperties;
7430 pointerProperties.clear();
7431 pointerProperties.id = 0;
7432 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7433
7434 PointerCoords pointerCoords;
7435 pointerCoords.clear();
7436
7437 size_t numAxes = mAxes.size();
7438 for (size_t i = 0; i < numAxes; i++) {
7439 const Axis& axis = mAxes.valueAt(i);
7440 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7441 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7442 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7443 axis.highCurrentValue);
7444 }
7445 }
7446
7447 // Moving a joystick axis should not wake the device because joysticks can
7448 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7449 // button will likely wake the device.
7450 // TODO: Use the input device configuration to control this behavior more finely.
7451 uint32_t policyFlags = 0;
7452
Prabir Pradhan42611e02018-11-27 14:04:02 -08007453 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007454 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7455 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07007456 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
7457 &pointerProperties, &pointerCoords, 0, 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07007458 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7459 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007460 getListener()->notifyMotion(&args);
7461}
7462
7463void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7464 int32_t axis, float value) {
7465 pointerCoords->setAxisValue(axis, value);
7466 /* In order to ease the transition for developers from using the old axes
7467 * to the newer, more semantically correct axes, we'll continue to produce
7468 * values for the old axes as mirrors of the value of their corresponding
7469 * new axes. */
7470 int32_t compatAxis = getCompatAxis(axis);
7471 if (compatAxis >= 0) {
7472 pointerCoords->setAxisValue(compatAxis, value);
7473 }
7474}
7475
7476bool JoystickInputMapper::filterAxes(bool force) {
7477 bool atLeastOneSignificantChange = force;
7478 size_t numAxes = mAxes.size();
7479 for (size_t i = 0; i < numAxes; i++) {
7480 Axis& axis = mAxes.editValueAt(i);
7481 if (force || hasValueChangedSignificantly(axis.filter,
7482 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7483 axis.currentValue = axis.newValue;
7484 atLeastOneSignificantChange = true;
7485 }
7486 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7487 if (force || hasValueChangedSignificantly(axis.filter,
7488 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7489 axis.highCurrentValue = axis.highNewValue;
7490 atLeastOneSignificantChange = true;
7491 }
7492 }
7493 }
7494 return atLeastOneSignificantChange;
7495}
7496
7497bool JoystickInputMapper::hasValueChangedSignificantly(
7498 float filter, float newValue, float currentValue, float min, float max) {
7499 if (newValue != currentValue) {
7500 // Filter out small changes in value unless the value is converging on the axis
7501 // bounds or center point. This is intended to reduce the amount of information
7502 // sent to applications by particularly noisy joysticks (such as PS3).
7503 if (fabs(newValue - currentValue) > filter
7504 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7505 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7506 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7507 return true;
7508 }
7509 }
7510 return false;
7511}
7512
7513bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7514 float filter, float newValue, float currentValue, float thresholdValue) {
7515 float newDistance = fabs(newValue - thresholdValue);
7516 if (newDistance < filter) {
7517 float oldDistance = fabs(currentValue - thresholdValue);
7518 if (newDistance < oldDistance) {
7519 return true;
7520 }
7521 }
7522 return false;
7523}
7524
7525} // namespace android