blob: b4c6b3326c7fc812710db1752bff1084ef31f234 [file] [log] [blame]
Michael Wrightd02c5b62014-02-10 15:10:22 -08001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "InputReader"
18
19//#define LOG_NDEBUG 0
20
21// Log debug messages for each raw event received from the EventHub.
22#define DEBUG_RAW_EVENTS 0
23
24// Log debug messages about touch screen filtering hacks.
25#define DEBUG_HACKS 0
26
27// Log debug messages about virtual key processing.
28#define DEBUG_VIRTUAL_KEYS 0
29
30// Log debug messages about pointers.
31#define DEBUG_POINTERS 0
32
33// Log debug messages about pointer assignment calculations.
34#define DEBUG_POINTER_ASSIGNMENT 0
35
36// Log debug messages about gesture detection.
37#define DEBUG_GESTURES 0
38
39// Log debug messages about the vibrator.
40#define DEBUG_VIBRATOR 0
41
Michael Wright842500e2015-03-13 17:32:02 -070042// Log debug messages about fusing stylus data.
43#define DEBUG_STYLUS_FUSION 0
44
Michael Wrightd02c5b62014-02-10 15:10:22 -080045#include "InputReader.h"
46
Mark Salyzyna5e161b2016-09-29 08:08:05 -070047#include <errno.h>
Michael Wright842500e2015-03-13 17:32:02 -070048#include <inttypes.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070049#include <limits.h>
50#include <math.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080051#include <stddef.h>
52#include <stdlib.h>
53#include <unistd.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070054
Mark Salyzyn7823e122016-09-29 08:08:05 -070055#include <log/log.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070056
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080057#include <android-base/stringprintf.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070058#include <input/Keyboard.h>
59#include <input/VirtualKeyMap.h>
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080060#include <statslog.h>
Michael Wrightd02c5b62014-02-10 15:10:22 -080061
62#define INDENT " "
63#define INDENT2 " "
64#define INDENT3 " "
65#define INDENT4 " "
66#define INDENT5 " "
67
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080068using android::base::StringPrintf;
69
Michael Wrightd02c5b62014-02-10 15:10:22 -080070namespace android {
71
72// --- Constants ---
73
74// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080075static constexpr size_t MAX_SLOTS = 32;
Michael Wrightd02c5b62014-02-10 15:10:22 -080076
Michael Wright842500e2015-03-13 17:32:02 -070077// Maximum amount of latency to add to touch events while waiting for data from an
78// external stylus.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080079static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070080
Michael Wright43fd19f2015-04-21 19:02:58 +010081// Maximum amount of time to wait on touch data before pushing out new pressure data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080082static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
Michael Wright43fd19f2015-04-21 19:02:58 +010083
84// Artificial latency on synthetic events created from stylus data without corresponding touch
85// data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080086static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
87
88// How often to report input event statistics
89static constexpr nsecs_t STATISTICS_REPORT_FREQUENCY = seconds_to_nanoseconds(5 * 60);
Michael Wright43fd19f2015-04-21 19:02:58 +010090
Michael Wrightd02c5b62014-02-10 15:10:22 -080091// --- Static Functions ---
92
93template<typename T>
94inline static T abs(const T& value) {
95 return value < 0 ? - value : value;
96}
97
98template<typename T>
99inline static T min(const T& a, const T& b) {
100 return a < b ? a : b;
101}
102
103template<typename T>
104inline static void swap(T& a, T& b) {
105 T temp = a;
106 a = b;
107 b = temp;
108}
109
110inline static float avg(float x, float y) {
111 return (x + y) / 2;
112}
113
114inline static float distance(float x1, float y1, float x2, float y2) {
115 return hypotf(x1 - x2, y1 - y2);
116}
117
118inline static int32_t signExtendNybble(int32_t value) {
119 return value >= 8 ? value - 16 : value;
120}
121
122static inline const char* toString(bool value) {
123 return value ? "true" : "false";
124}
125
126static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
127 const int32_t map[][4], size_t mapSize) {
128 if (orientation != DISPLAY_ORIENTATION_0) {
129 for (size_t i = 0; i < mapSize; i++) {
130 if (value == map[i][0]) {
131 return map[i][orientation];
132 }
133 }
134 }
135 return value;
136}
137
138static const int32_t keyCodeRotationMap[][4] = {
139 // key codes enumerated counter-clockwise with the original (unrotated) key first
140 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
141 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
142 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
143 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
144 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700145 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
146 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
147 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
148 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
149 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
150 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
151 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
152 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800153};
154static const size_t keyCodeRotationMapSize =
155 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
156
Ivan Podogovb9afef32017-02-13 15:34:32 +0000157static int32_t rotateStemKey(int32_t value, int32_t orientation,
158 const int32_t map[][2], size_t mapSize) {
159 if (orientation == DISPLAY_ORIENTATION_180) {
160 for (size_t i = 0; i < mapSize; i++) {
161 if (value == map[i][0]) {
162 return map[i][1];
163 }
164 }
165 }
166 return value;
167}
168
169// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
170static int32_t stemKeyRotationMap[][2] = {
171 // key codes enumerated with the original (unrotated) key first
172 // no rotation, 180 degree rotation
173 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
174 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
175 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
176 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
177};
178static const size_t stemKeyRotationMapSize =
179 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
180
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000182 keyCode = rotateStemKey(keyCode, orientation,
183 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800184 return rotateValueUsingRotationMap(keyCode, orientation,
185 keyCodeRotationMap, keyCodeRotationMapSize);
186}
187
188static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
189 float temp;
190 switch (orientation) {
191 case DISPLAY_ORIENTATION_90:
192 temp = *deltaX;
193 *deltaX = *deltaY;
194 *deltaY = -temp;
195 break;
196
197 case DISPLAY_ORIENTATION_180:
198 *deltaX = -*deltaX;
199 *deltaY = -*deltaY;
200 break;
201
202 case DISPLAY_ORIENTATION_270:
203 temp = *deltaX;
204 *deltaX = -*deltaY;
205 *deltaY = temp;
206 break;
207 }
208}
209
210static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
211 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
212}
213
214// Returns true if the pointer should be reported as being down given the specified
215// button states. This determines whether the event is reported as a touch event.
216static bool isPointerDown(int32_t buttonState) {
217 return buttonState &
218 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
219 | AMOTION_EVENT_BUTTON_TERTIARY);
220}
221
222static float calculateCommonVector(float a, float b) {
223 if (a > 0 && b > 0) {
224 return a < b ? a : b;
225 } else if (a < 0 && b < 0) {
226 return a > b ? a : b;
227 } else {
228 return 0;
229 }
230}
231
232static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100233 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800234 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
235 int32_t buttonState, int32_t keyCode) {
236 if (
237 (action == AKEY_EVENT_ACTION_DOWN
238 && !(lastButtonState & buttonState)
239 && (currentButtonState & buttonState))
240 || (action == AKEY_EVENT_ACTION_UP
241 && (lastButtonState & buttonState)
242 && !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800243 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
244 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800245 context->getListener()->notifyKey(&args);
246 }
247}
248
249static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100250 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100252 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253 lastButtonState, currentButtonState,
254 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100255 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800256 lastButtonState, currentButtonState,
257 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
258}
259
260
Michael Wrightd02c5b62014-02-10 15:10:22 -0800261// --- InputReader ---
262
263InputReader::InputReader(const sp<EventHubInterface>& eventHub,
264 const sp<InputReaderPolicyInterface>& policy,
265 const sp<InputListenerInterface>& listener) :
266 mContext(this), mEventHub(eventHub), mPolicy(policy),
Prabir Pradhan42611e02018-11-27 14:04:02 -0800267 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800268 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
269 mConfigurationChangesToRefresh(0) {
270 mQueuedListener = new QueuedInputListener(listener);
271
272 { // acquire lock
273 AutoMutex _l(mLock);
274
275 refreshConfigurationLocked(0);
276 updateGlobalMetaStateLocked();
277 } // release lock
278}
279
280InputReader::~InputReader() {
281 for (size_t i = 0; i < mDevices.size(); i++) {
282 delete mDevices.valueAt(i);
283 }
284}
285
286void InputReader::loopOnce() {
287 int32_t oldGeneration;
288 int32_t timeoutMillis;
289 bool inputDevicesChanged = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800290 std::vector<InputDeviceInfo> inputDevices;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800291 { // acquire lock
292 AutoMutex _l(mLock);
293
294 oldGeneration = mGeneration;
295 timeoutMillis = -1;
296
297 uint32_t changes = mConfigurationChangesToRefresh;
298 if (changes) {
299 mConfigurationChangesToRefresh = 0;
300 timeoutMillis = 0;
301 refreshConfigurationLocked(changes);
302 } else if (mNextTimeout != LLONG_MAX) {
303 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
304 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
305 }
306 } // release lock
307
308 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
309
310 { // acquire lock
311 AutoMutex _l(mLock);
312 mReaderIsAliveCondition.broadcast();
313
314 if (count) {
315 processEventsLocked(mEventBuffer, count);
316 }
317
318 if (mNextTimeout != LLONG_MAX) {
319 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
320 if (now >= mNextTimeout) {
321#if DEBUG_RAW_EVENTS
322 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
323#endif
324 mNextTimeout = LLONG_MAX;
325 timeoutExpiredLocked(now);
326 }
327 }
328
329 if (oldGeneration != mGeneration) {
330 inputDevicesChanged = true;
331 getInputDevicesLocked(inputDevices);
332 }
333 } // release lock
334
335 // Send out a message that the describes the changed input devices.
336 if (inputDevicesChanged) {
337 mPolicy->notifyInputDevicesChanged(inputDevices);
338 }
339
340 // Flush queued events out to the listener.
341 // This must happen outside of the lock because the listener could potentially call
342 // back into the InputReader's methods, such as getScanCodeState, or become blocked
343 // on another thread similarly waiting to acquire the InputReader lock thereby
344 // resulting in a deadlock. This situation is actually quite plausible because the
345 // listener is actually the input dispatcher, which calls into the window manager,
346 // which occasionally calls into the input reader.
347 mQueuedListener->flush();
348}
349
350void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
351 for (const RawEvent* rawEvent = rawEvents; count;) {
352 int32_t type = rawEvent->type;
353 size_t batchSize = 1;
354 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
355 int32_t deviceId = rawEvent->deviceId;
356 while (batchSize < count) {
357 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
358 || rawEvent[batchSize].deviceId != deviceId) {
359 break;
360 }
361 batchSize += 1;
362 }
363#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700364 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800365#endif
366 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
367 } else {
368 switch (rawEvent->type) {
369 case EventHubInterface::DEVICE_ADDED:
370 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::DEVICE_REMOVED:
373 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
374 break;
375 case EventHubInterface::FINISHED_DEVICE_SCAN:
376 handleConfigurationChangedLocked(rawEvent->when);
377 break;
378 default:
379 ALOG_ASSERT(false); // can't happen
380 break;
381 }
382 }
383 count -= batchSize;
384 rawEvent += batchSize;
385 }
386}
387
388void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
389 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
390 if (deviceIndex >= 0) {
391 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
392 return;
393 }
394
395 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
396 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
397 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
398
399 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
400 device->configure(when, &mConfig, 0);
401 device->reset(when);
402
403 if (device->isIgnored()) {
404 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100405 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 } else {
407 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100408 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800409 }
410
411 mDevices.add(deviceId, device);
412 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700413
414 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
415 notifyExternalStylusPresenceChanged();
416 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417}
418
419void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700420 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800421 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
422 if (deviceIndex < 0) {
423 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
424 return;
425 }
426
427 device = mDevices.valueAt(deviceIndex);
428 mDevices.removeItemsAt(deviceIndex, 1);
429 bumpGenerationLocked();
430
431 if (device->isIgnored()) {
432 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100433 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 } else {
435 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100436 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800437 }
438
Michael Wright842500e2015-03-13 17:32:02 -0700439 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
440 notifyExternalStylusPresenceChanged();
441 }
442
Michael Wrightd02c5b62014-02-10 15:10:22 -0800443 device->reset(when);
444 delete device;
445}
446
447InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
448 const InputDeviceIdentifier& identifier, uint32_t classes) {
449 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
450 controllerNumber, identifier, classes);
451
452 // External devices.
453 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
454 device->setExternal(true);
455 }
456
Tim Kilbourn063ff532015-04-08 10:26:18 -0700457 // Devices with mics.
458 if (classes & INPUT_DEVICE_CLASS_MIC) {
459 device->setMic(true);
460 }
461
Michael Wrightd02c5b62014-02-10 15:10:22 -0800462 // Switch-like devices.
463 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
464 device->addMapper(new SwitchInputMapper(device));
465 }
466
Prashant Malani1941ff52015-08-11 18:29:28 -0700467 // Scroll wheel-like devices.
468 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
469 device->addMapper(new RotaryEncoderInputMapper(device));
470 }
471
Michael Wrightd02c5b62014-02-10 15:10:22 -0800472 // Vibrator-like devices.
473 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
474 device->addMapper(new VibratorInputMapper(device));
475 }
476
477 // Keyboard-like devices.
478 uint32_t keyboardSource = 0;
479 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
480 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
481 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
482 }
483 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
484 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
485 }
486 if (classes & INPUT_DEVICE_CLASS_DPAD) {
487 keyboardSource |= AINPUT_SOURCE_DPAD;
488 }
489 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
490 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
491 }
492
493 if (keyboardSource != 0) {
494 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
495 }
496
497 // Cursor-like devices.
498 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
499 device->addMapper(new CursorInputMapper(device));
500 }
501
502 // Touchscreens and touchpad devices.
503 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
504 device->addMapper(new MultiTouchInputMapper(device));
505 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
506 device->addMapper(new SingleTouchInputMapper(device));
507 }
508
509 // Joystick-like devices.
510 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
511 device->addMapper(new JoystickInputMapper(device));
512 }
513
Michael Wright842500e2015-03-13 17:32:02 -0700514 // External stylus-like devices.
515 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
516 device->addMapper(new ExternalStylusInputMapper(device));
517 }
518
Michael Wrightd02c5b62014-02-10 15:10:22 -0800519 return device;
520}
521
522void InputReader::processEventsForDeviceLocked(int32_t deviceId,
523 const RawEvent* rawEvents, size_t count) {
524 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
525 if (deviceIndex < 0) {
526 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
527 return;
528 }
529
530 InputDevice* device = mDevices.valueAt(deviceIndex);
531 if (device->isIgnored()) {
532 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
533 return;
534 }
535
536 device->process(rawEvents, count);
537}
538
539void InputReader::timeoutExpiredLocked(nsecs_t when) {
540 for (size_t i = 0; i < mDevices.size(); i++) {
541 InputDevice* device = mDevices.valueAt(i);
542 if (!device->isIgnored()) {
543 device->timeoutExpired(when);
544 }
545 }
546}
547
548void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
549 // Reset global meta state because it depends on the list of all configured devices.
550 updateGlobalMetaStateLocked();
551
552 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800553 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800554 mQueuedListener->notifyConfigurationChanged(&args);
555}
556
557void InputReader::refreshConfigurationLocked(uint32_t changes) {
558 mPolicy->getReaderConfiguration(&mConfig);
559 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
560
561 if (changes) {
562 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
563 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
564
565 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
566 mEventHub->requestReopenDevices();
567 } else {
568 for (size_t i = 0; i < mDevices.size(); i++) {
569 InputDevice* device = mDevices.valueAt(i);
570 device->configure(now, &mConfig, changes);
571 }
572 }
573 }
574}
575
576void InputReader::updateGlobalMetaStateLocked() {
577 mGlobalMetaState = 0;
578
579 for (size_t i = 0; i < mDevices.size(); i++) {
580 InputDevice* device = mDevices.valueAt(i);
581 mGlobalMetaState |= device->getMetaState();
582 }
583}
584
585int32_t InputReader::getGlobalMetaStateLocked() {
586 return mGlobalMetaState;
587}
588
Michael Wright842500e2015-03-13 17:32:02 -0700589void InputReader::notifyExternalStylusPresenceChanged() {
590 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
591}
592
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800593void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700594 for (size_t i = 0; i < mDevices.size(); i++) {
595 InputDevice* device = mDevices.valueAt(i);
596 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800597 InputDeviceInfo info;
598 device->getDeviceInfo(&info);
599 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700600 }
601 }
602}
603
604void InputReader::dispatchExternalStylusState(const StylusState& state) {
605 for (size_t i = 0; i < mDevices.size(); i++) {
606 InputDevice* device = mDevices.valueAt(i);
607 device->updateExternalStylusState(state);
608 }
609}
610
Michael Wrightd02c5b62014-02-10 15:10:22 -0800611void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
612 mDisableVirtualKeysTimeout = time;
613}
614
615bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
616 InputDevice* device, int32_t keyCode, int32_t scanCode) {
617 if (now < mDisableVirtualKeysTimeout) {
618 ALOGI("Dropping virtual key from device %s because virtual keys are "
619 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100620 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 (mDisableVirtualKeysTimeout - now) * 0.000001,
622 keyCode, scanCode);
623 return true;
624 } else {
625 return false;
626 }
627}
628
629void InputReader::fadePointerLocked() {
630 for (size_t i = 0; i < mDevices.size(); i++) {
631 InputDevice* device = mDevices.valueAt(i);
632 device->fadePointer();
633 }
634}
635
636void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
637 if (when < mNextTimeout) {
638 mNextTimeout = when;
639 mEventHub->wake();
640 }
641}
642
643int32_t InputReader::bumpGenerationLocked() {
644 return ++mGeneration;
645}
646
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800647void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800648 AutoMutex _l(mLock);
649 getInputDevicesLocked(outInputDevices);
650}
651
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800652void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800653 outInputDevices.clear();
654
655 size_t numDevices = mDevices.size();
656 for (size_t i = 0; i < numDevices; i++) {
657 InputDevice* device = mDevices.valueAt(i);
658 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800659 InputDeviceInfo info;
660 device->getDeviceInfo(&info);
661 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800662 }
663 }
664}
665
666int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
667 int32_t keyCode) {
668 AutoMutex _l(mLock);
669
670 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
671}
672
673int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
674 int32_t scanCode) {
675 AutoMutex _l(mLock);
676
677 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
678}
679
680int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
681 AutoMutex _l(mLock);
682
683 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
684}
685
686int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
687 GetStateFunc getStateFunc) {
688 int32_t result = AKEY_STATE_UNKNOWN;
689 if (deviceId >= 0) {
690 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
691 if (deviceIndex >= 0) {
692 InputDevice* device = mDevices.valueAt(deviceIndex);
693 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
694 result = (device->*getStateFunc)(sourceMask, code);
695 }
696 }
697 } else {
698 size_t numDevices = mDevices.size();
699 for (size_t i = 0; i < numDevices; i++) {
700 InputDevice* device = mDevices.valueAt(i);
701 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
702 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
703 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
704 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
705 if (currentResult >= AKEY_STATE_DOWN) {
706 return currentResult;
707 } else if (currentResult == AKEY_STATE_UP) {
708 result = currentResult;
709 }
710 }
711 }
712 }
713 return result;
714}
715
Andrii Kulian763a3a42016-03-08 10:46:16 -0800716void InputReader::toggleCapsLockState(int32_t deviceId) {
717 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
718 if (deviceIndex < 0) {
719 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
720 return;
721 }
722
723 InputDevice* device = mDevices.valueAt(deviceIndex);
724 if (device->isIgnored()) {
725 return;
726 }
727
728 device->updateMetaState(AKEYCODE_CAPS_LOCK);
729}
730
Michael Wrightd02c5b62014-02-10 15:10:22 -0800731bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
732 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
733 AutoMutex _l(mLock);
734
735 memset(outFlags, 0, numCodes);
736 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
737}
738
739bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
740 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
741 bool result = false;
742 if (deviceId >= 0) {
743 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
744 if (deviceIndex >= 0) {
745 InputDevice* device = mDevices.valueAt(deviceIndex);
746 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
747 result = device->markSupportedKeyCodes(sourceMask,
748 numCodes, keyCodes, outFlags);
749 }
750 }
751 } else {
752 size_t numDevices = mDevices.size();
753 for (size_t i = 0; i < numDevices; i++) {
754 InputDevice* device = mDevices.valueAt(i);
755 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
756 result |= device->markSupportedKeyCodes(sourceMask,
757 numCodes, keyCodes, outFlags);
758 }
759 }
760 }
761 return result;
762}
763
764void InputReader::requestRefreshConfiguration(uint32_t changes) {
765 AutoMutex _l(mLock);
766
767 if (changes) {
768 bool needWake = !mConfigurationChangesToRefresh;
769 mConfigurationChangesToRefresh |= changes;
770
771 if (needWake) {
772 mEventHub->wake();
773 }
774 }
775}
776
777void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
778 ssize_t repeat, int32_t token) {
779 AutoMutex _l(mLock);
780
781 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
782 if (deviceIndex >= 0) {
783 InputDevice* device = mDevices.valueAt(deviceIndex);
784 device->vibrate(pattern, patternSize, repeat, token);
785 }
786}
787
788void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
789 AutoMutex _l(mLock);
790
791 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
792 if (deviceIndex >= 0) {
793 InputDevice* device = mDevices.valueAt(deviceIndex);
794 device->cancelVibrate(token);
795 }
796}
797
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700798bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
799 AutoMutex _l(mLock);
800
801 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
802 if (deviceIndex >= 0) {
803 InputDevice* device = mDevices.valueAt(deviceIndex);
804 return device->isEnabled();
805 }
806 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
807 return false;
808}
809
Arthur Hungc23540e2018-11-29 20:42:11 +0800810bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
811 AutoMutex _l(mLock);
812
813 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
814 if (deviceIndex < 0) {
815 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
816 return false;
817 }
818
819 InputDevice* device = mDevices.valueAt(deviceIndex);
820 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
821 // No associated display. By default, can dispatch to all displays.
822 if (!associatedDisplayId) {
823 return true;
824 }
825
826 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
827 ALOGW("Device has associated, but no associated display id.");
828 return true;
829 }
830
831 return *associatedDisplayId == displayId;
832}
833
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800834void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 AutoMutex _l(mLock);
836
837 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800838 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800840 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841
842 for (size_t i = 0; i < mDevices.size(); i++) {
843 mDevices.valueAt(i)->dump(dump);
844 }
845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += INDENT "Configuration:\n";
847 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
849 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100852 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800854 dump += "]\n";
855 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 mConfig.virtualKeyQuietTime * 0.000001f);
857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
860 mConfig.pointerVelocityControlParameters.scale,
861 mConfig.pointerVelocityControlParameters.lowThreshold,
862 mConfig.pointerVelocityControlParameters.highThreshold,
863 mConfig.pointerVelocityControlParameters.acceleration);
864
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
867 mConfig.wheelVelocityControlParameters.scale,
868 mConfig.wheelVelocityControlParameters.lowThreshold,
869 mConfig.wheelVelocityControlParameters.highThreshold,
870 mConfig.wheelVelocityControlParameters.acceleration);
871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += StringPrintf(INDENT2 "PointerGesture:\n");
873 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800875 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800877 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800881 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700897
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800898 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700899 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900}
901
902void InputReader::monitor() {
903 // Acquire and release the lock to ensure that the reader has not deadlocked.
904 mLock.lock();
905 mEventHub->wake();
906 mReaderIsAliveCondition.wait(mLock);
907 mLock.unlock();
908
909 // Check the EventHub
910 mEventHub->monitor();
911}
912
913
914// --- InputReader::ContextImpl ---
915
916InputReader::ContextImpl::ContextImpl(InputReader* reader) :
917 mReader(reader) {
918}
919
920void InputReader::ContextImpl::updateGlobalMetaState() {
921 // lock is already held by the input loop
922 mReader->updateGlobalMetaStateLocked();
923}
924
925int32_t InputReader::ContextImpl::getGlobalMetaState() {
926 // lock is already held by the input loop
927 return mReader->getGlobalMetaStateLocked();
928}
929
930void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
931 // lock is already held by the input loop
932 mReader->disableVirtualKeysUntilLocked(time);
933}
934
935bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
936 InputDevice* device, int32_t keyCode, int32_t scanCode) {
937 // lock is already held by the input loop
938 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
939}
940
941void InputReader::ContextImpl::fadePointer() {
942 // lock is already held by the input loop
943 mReader->fadePointerLocked();
944}
945
946void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
947 // lock is already held by the input loop
948 mReader->requestTimeoutAtTimeLocked(when);
949}
950
951int32_t InputReader::ContextImpl::bumpGeneration() {
952 // lock is already held by the input loop
953 return mReader->bumpGenerationLocked();
954}
955
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800956void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700957 // lock is already held by whatever called refreshConfigurationLocked
958 mReader->getExternalStylusDevicesLocked(outDevices);
959}
960
961void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
962 mReader->dispatchExternalStylusState(state);
963}
964
Michael Wrightd02c5b62014-02-10 15:10:22 -0800965InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
966 return mReader->mPolicy.get();
967}
968
969InputListenerInterface* InputReader::ContextImpl::getListener() {
970 return mReader->mQueuedListener.get();
971}
972
973EventHubInterface* InputReader::ContextImpl::getEventHub() {
974 return mReader->mEventHub.get();
975}
976
Prabir Pradhan42611e02018-11-27 14:04:02 -0800977uint32_t InputReader::ContextImpl::getNextSequenceNum() {
978 return (mReader->mNextSequenceNum)++;
979}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800980
Michael Wrightd02c5b62014-02-10 15:10:22 -0800981// --- InputDevice ---
982
983InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
984 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
985 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
986 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700987 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800988}
989
990InputDevice::~InputDevice() {
991 size_t numMappers = mMappers.size();
992 for (size_t i = 0; i < numMappers; i++) {
993 delete mMappers[i];
994 }
995 mMappers.clear();
996}
997
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700998bool InputDevice::isEnabled() {
999 return getEventHub()->isDeviceEnabled(mId);
1000}
1001
1002void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1003 if (isEnabled() == enabled) {
1004 return;
1005 }
1006
1007 if (enabled) {
1008 getEventHub()->enableDevice(mId);
1009 reset(when);
1010 } else {
1011 reset(when);
1012 getEventHub()->disableDevice(mId);
1013 }
1014 // Must change generation to flag this device as changed
1015 bumpGeneration();
1016}
1017
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001018void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001020 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001022 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001023 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001024 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1025 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001026 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1027 if (mAssociatedDisplayPort) {
1028 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1029 } else {
1030 dump += "<none>\n";
1031 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001032 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1033 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1034 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001035
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001036 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1037 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001038 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001039 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001040 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041 const char* label = getAxisLabel(range.axis);
1042 char name[32];
1043 if (label) {
1044 strncpy(name, label, sizeof(name));
1045 name[sizeof(name) - 1] = '\0';
1046 } else {
1047 snprintf(name, sizeof(name), "%d", range.axis);
1048 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001049 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1051 name, range.source, range.min, range.max, range.flat, range.fuzz,
1052 range.resolution);
1053 }
1054 }
1055
1056 size_t numMappers = mMappers.size();
1057 for (size_t i = 0; i < numMappers; i++) {
1058 InputMapper* mapper = mMappers[i];
1059 mapper->dump(dump);
1060 }
1061}
1062
1063void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001064 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001065}
1066
1067void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1068 mSources = 0;
1069
1070 if (!isIgnored()) {
1071 if (!changes) { // first time only
1072 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1073 }
1074
1075 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1076 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1077 sp<KeyCharacterMap> keyboardLayout =
1078 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1079 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1080 bumpGeneration();
1081 }
1082 }
1083 }
1084
1085 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1086 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001087 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001088 if (mAlias != alias) {
1089 mAlias = alias;
1090 bumpGeneration();
1091 }
1092 }
1093 }
1094
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001095 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1096 ssize_t index = config->disabledDevices.indexOf(mId);
1097 bool enabled = index < 0;
1098 setEnabled(enabled, when);
1099 }
1100
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001101 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1102 // In most situations, no port will be specified.
1103 mAssociatedDisplayPort = std::nullopt;
1104 // Find the display port that corresponds to the current input port.
1105 const std::string& inputPort = mIdentifier.location;
1106 if (!inputPort.empty()) {
1107 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1108 const auto& displayPort = ports.find(inputPort);
1109 if (displayPort != ports.end()) {
1110 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1111 }
1112 }
1113 }
1114
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001115 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 mapper->configure(when, config, changes);
1117 mSources |= mapper->getSources();
1118 }
1119 }
1120}
1121
1122void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001123 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001124 mapper->reset(when);
1125 }
1126
1127 mContext->updateGlobalMetaState();
1128
1129 notifyReset(when);
1130}
1131
1132void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1133 // Process all of the events in order for each mapper.
1134 // We cannot simply ask each mapper to process them in bulk because mappers may
1135 // have side-effects that must be interleaved. For example, joystick movement events and
1136 // gamepad button presses are handled by different mappers but they should be dispatched
1137 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001138 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001140 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001141 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1142 rawEvent->when);
1143#endif
1144
1145 if (mDropUntilNextSync) {
1146 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1147 mDropUntilNextSync = false;
1148#if DEBUG_RAW_EVENTS
1149 ALOGD("Recovered from input event buffer overrun.");
1150#endif
1151 } else {
1152#if DEBUG_RAW_EVENTS
1153 ALOGD("Dropped input event while waiting for next input sync.");
1154#endif
1155 }
1156 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001157 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001158 mDropUntilNextSync = true;
1159 reset(rawEvent->when);
1160 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001161 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 mapper->process(rawEvent);
1163 }
1164 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001165 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001166 }
1167}
1168
1169void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001170 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001171 mapper->timeoutExpired(when);
1172 }
1173}
1174
Michael Wright842500e2015-03-13 17:32:02 -07001175void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001176 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001177 mapper->updateExternalStylusState(state);
1178 }
1179}
1180
Michael Wrightd02c5b62014-02-10 15:10:22 -08001181void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1182 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001183 mIsExternal, mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001184 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001185 mapper->populateDeviceInfo(outDeviceInfo);
1186 }
1187}
1188
1189int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1190 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1191}
1192
1193int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1194 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1195}
1196
1197int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1198 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1199}
1200
1201int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1202 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001203 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001204 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1205 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1206 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1207 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1208 if (currentResult >= AKEY_STATE_DOWN) {
1209 return currentResult;
1210 } else if (currentResult == AKEY_STATE_UP) {
1211 result = currentResult;
1212 }
1213 }
1214 }
1215 return result;
1216}
1217
1218bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1219 const int32_t* keyCodes, uint8_t* outFlags) {
1220 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001221 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001222 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1223 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1224 }
1225 }
1226 return result;
1227}
1228
1229void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1230 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001231 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001232 mapper->vibrate(pattern, patternSize, repeat, token);
1233 }
1234}
1235
1236void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001237 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 mapper->cancelVibrate(token);
1239 }
1240}
1241
Jeff Brownc9aa6282015-02-11 19:03:28 -08001242void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001243 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001244 mapper->cancelTouch(when);
1245 }
1246}
1247
Michael Wrightd02c5b62014-02-10 15:10:22 -08001248int32_t InputDevice::getMetaState() {
1249 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001250 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001251 result |= mapper->getMetaState();
1252 }
1253 return result;
1254}
1255
Andrii Kulian763a3a42016-03-08 10:46:16 -08001256void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001257 for (InputMapper* mapper : mMappers) {
1258 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001259 }
1260}
1261
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001263 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001264 mapper->fadePointer();
1265 }
1266}
1267
1268void InputDevice::bumpGeneration() {
1269 mGeneration = mContext->bumpGeneration();
1270}
1271
1272void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001273 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001274 mContext->getListener()->notifyDeviceReset(&args);
1275}
1276
Arthur Hungc23540e2018-11-29 20:42:11 +08001277std::optional<int32_t> InputDevice::getAssociatedDisplay() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001278 for (InputMapper* mapper : mMappers) {
Arthur Hungc23540e2018-11-29 20:42:11 +08001279 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1280 if (associatedDisplayId) {
1281 return associatedDisplayId;
1282 }
1283 }
1284
1285 return std::nullopt;
1286}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001287
1288// --- CursorButtonAccumulator ---
1289
1290CursorButtonAccumulator::CursorButtonAccumulator() {
1291 clearButtons();
1292}
1293
1294void CursorButtonAccumulator::reset(InputDevice* device) {
1295 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1296 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1297 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1298 mBtnBack = device->isKeyPressed(BTN_BACK);
1299 mBtnSide = device->isKeyPressed(BTN_SIDE);
1300 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1301 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1302 mBtnTask = device->isKeyPressed(BTN_TASK);
1303}
1304
1305void CursorButtonAccumulator::clearButtons() {
1306 mBtnLeft = 0;
1307 mBtnRight = 0;
1308 mBtnMiddle = 0;
1309 mBtnBack = 0;
1310 mBtnSide = 0;
1311 mBtnForward = 0;
1312 mBtnExtra = 0;
1313 mBtnTask = 0;
1314}
1315
1316void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1317 if (rawEvent->type == EV_KEY) {
1318 switch (rawEvent->code) {
1319 case BTN_LEFT:
1320 mBtnLeft = rawEvent->value;
1321 break;
1322 case BTN_RIGHT:
1323 mBtnRight = rawEvent->value;
1324 break;
1325 case BTN_MIDDLE:
1326 mBtnMiddle = rawEvent->value;
1327 break;
1328 case BTN_BACK:
1329 mBtnBack = rawEvent->value;
1330 break;
1331 case BTN_SIDE:
1332 mBtnSide = rawEvent->value;
1333 break;
1334 case BTN_FORWARD:
1335 mBtnForward = rawEvent->value;
1336 break;
1337 case BTN_EXTRA:
1338 mBtnExtra = rawEvent->value;
1339 break;
1340 case BTN_TASK:
1341 mBtnTask = rawEvent->value;
1342 break;
1343 }
1344 }
1345}
1346
1347uint32_t CursorButtonAccumulator::getButtonState() const {
1348 uint32_t result = 0;
1349 if (mBtnLeft) {
1350 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1351 }
1352 if (mBtnRight) {
1353 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1354 }
1355 if (mBtnMiddle) {
1356 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1357 }
1358 if (mBtnBack || mBtnSide) {
1359 result |= AMOTION_EVENT_BUTTON_BACK;
1360 }
1361 if (mBtnForward || mBtnExtra) {
1362 result |= AMOTION_EVENT_BUTTON_FORWARD;
1363 }
1364 return result;
1365}
1366
1367
1368// --- CursorMotionAccumulator ---
1369
1370CursorMotionAccumulator::CursorMotionAccumulator() {
1371 clearRelativeAxes();
1372}
1373
1374void CursorMotionAccumulator::reset(InputDevice* device) {
1375 clearRelativeAxes();
1376}
1377
1378void CursorMotionAccumulator::clearRelativeAxes() {
1379 mRelX = 0;
1380 mRelY = 0;
1381}
1382
1383void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1384 if (rawEvent->type == EV_REL) {
1385 switch (rawEvent->code) {
1386 case REL_X:
1387 mRelX = rawEvent->value;
1388 break;
1389 case REL_Y:
1390 mRelY = rawEvent->value;
1391 break;
1392 }
1393 }
1394}
1395
1396void CursorMotionAccumulator::finishSync() {
1397 clearRelativeAxes();
1398}
1399
1400
1401// --- CursorScrollAccumulator ---
1402
1403CursorScrollAccumulator::CursorScrollAccumulator() :
1404 mHaveRelWheel(false), mHaveRelHWheel(false) {
1405 clearRelativeAxes();
1406}
1407
1408void CursorScrollAccumulator::configure(InputDevice* device) {
1409 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1410 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1411}
1412
1413void CursorScrollAccumulator::reset(InputDevice* device) {
1414 clearRelativeAxes();
1415}
1416
1417void CursorScrollAccumulator::clearRelativeAxes() {
1418 mRelWheel = 0;
1419 mRelHWheel = 0;
1420}
1421
1422void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1423 if (rawEvent->type == EV_REL) {
1424 switch (rawEvent->code) {
1425 case REL_WHEEL:
1426 mRelWheel = rawEvent->value;
1427 break;
1428 case REL_HWHEEL:
1429 mRelHWheel = rawEvent->value;
1430 break;
1431 }
1432 }
1433}
1434
1435void CursorScrollAccumulator::finishSync() {
1436 clearRelativeAxes();
1437}
1438
1439
1440// --- TouchButtonAccumulator ---
1441
1442TouchButtonAccumulator::TouchButtonAccumulator() :
1443 mHaveBtnTouch(false), mHaveStylus(false) {
1444 clearButtons();
1445}
1446
1447void TouchButtonAccumulator::configure(InputDevice* device) {
1448 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1449 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1450 || device->hasKey(BTN_TOOL_RUBBER)
1451 || device->hasKey(BTN_TOOL_BRUSH)
1452 || device->hasKey(BTN_TOOL_PENCIL)
1453 || device->hasKey(BTN_TOOL_AIRBRUSH);
1454}
1455
1456void TouchButtonAccumulator::reset(InputDevice* device) {
1457 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1458 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001459 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1460 mBtnStylus2 =
1461 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001462 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1463 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1464 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1465 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1466 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1467 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1468 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1469 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1470 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1471 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1472 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1473}
1474
1475void TouchButtonAccumulator::clearButtons() {
1476 mBtnTouch = 0;
1477 mBtnStylus = 0;
1478 mBtnStylus2 = 0;
1479 mBtnToolFinger = 0;
1480 mBtnToolPen = 0;
1481 mBtnToolRubber = 0;
1482 mBtnToolBrush = 0;
1483 mBtnToolPencil = 0;
1484 mBtnToolAirbrush = 0;
1485 mBtnToolMouse = 0;
1486 mBtnToolLens = 0;
1487 mBtnToolDoubleTap = 0;
1488 mBtnToolTripleTap = 0;
1489 mBtnToolQuadTap = 0;
1490}
1491
1492void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1493 if (rawEvent->type == EV_KEY) {
1494 switch (rawEvent->code) {
1495 case BTN_TOUCH:
1496 mBtnTouch = rawEvent->value;
1497 break;
1498 case BTN_STYLUS:
1499 mBtnStylus = rawEvent->value;
1500 break;
1501 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001502 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001503 mBtnStylus2 = rawEvent->value;
1504 break;
1505 case BTN_TOOL_FINGER:
1506 mBtnToolFinger = rawEvent->value;
1507 break;
1508 case BTN_TOOL_PEN:
1509 mBtnToolPen = rawEvent->value;
1510 break;
1511 case BTN_TOOL_RUBBER:
1512 mBtnToolRubber = rawEvent->value;
1513 break;
1514 case BTN_TOOL_BRUSH:
1515 mBtnToolBrush = rawEvent->value;
1516 break;
1517 case BTN_TOOL_PENCIL:
1518 mBtnToolPencil = rawEvent->value;
1519 break;
1520 case BTN_TOOL_AIRBRUSH:
1521 mBtnToolAirbrush = rawEvent->value;
1522 break;
1523 case BTN_TOOL_MOUSE:
1524 mBtnToolMouse = rawEvent->value;
1525 break;
1526 case BTN_TOOL_LENS:
1527 mBtnToolLens = rawEvent->value;
1528 break;
1529 case BTN_TOOL_DOUBLETAP:
1530 mBtnToolDoubleTap = rawEvent->value;
1531 break;
1532 case BTN_TOOL_TRIPLETAP:
1533 mBtnToolTripleTap = rawEvent->value;
1534 break;
1535 case BTN_TOOL_QUADTAP:
1536 mBtnToolQuadTap = rawEvent->value;
1537 break;
1538 }
1539 }
1540}
1541
1542uint32_t TouchButtonAccumulator::getButtonState() const {
1543 uint32_t result = 0;
1544 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001545 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001546 }
1547 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001548 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001549 }
1550 return result;
1551}
1552
1553int32_t TouchButtonAccumulator::getToolType() const {
1554 if (mBtnToolMouse || mBtnToolLens) {
1555 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1556 }
1557 if (mBtnToolRubber) {
1558 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1559 }
1560 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1561 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1562 }
1563 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1564 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1565 }
1566 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1567}
1568
1569bool TouchButtonAccumulator::isToolActive() const {
1570 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1571 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1572 || mBtnToolMouse || mBtnToolLens
1573 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1574}
1575
1576bool TouchButtonAccumulator::isHovering() const {
1577 return mHaveBtnTouch && !mBtnTouch;
1578}
1579
1580bool TouchButtonAccumulator::hasStylus() const {
1581 return mHaveStylus;
1582}
1583
1584
1585// --- RawPointerAxes ---
1586
1587RawPointerAxes::RawPointerAxes() {
1588 clear();
1589}
1590
1591void RawPointerAxes::clear() {
1592 x.clear();
1593 y.clear();
1594 pressure.clear();
1595 touchMajor.clear();
1596 touchMinor.clear();
1597 toolMajor.clear();
1598 toolMinor.clear();
1599 orientation.clear();
1600 distance.clear();
1601 tiltX.clear();
1602 tiltY.clear();
1603 trackingId.clear();
1604 slot.clear();
1605}
1606
1607
1608// --- RawPointerData ---
1609
1610RawPointerData::RawPointerData() {
1611 clear();
1612}
1613
1614void RawPointerData::clear() {
1615 pointerCount = 0;
1616 clearIdBits();
1617}
1618
1619void RawPointerData::copyFrom(const RawPointerData& other) {
1620 pointerCount = other.pointerCount;
1621 hoveringIdBits = other.hoveringIdBits;
1622 touchingIdBits = other.touchingIdBits;
1623
1624 for (uint32_t i = 0; i < pointerCount; i++) {
1625 pointers[i] = other.pointers[i];
1626
1627 int id = pointers[i].id;
1628 idToIndex[id] = other.idToIndex[id];
1629 }
1630}
1631
1632void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1633 float x = 0, y = 0;
1634 uint32_t count = touchingIdBits.count();
1635 if (count) {
1636 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1637 uint32_t id = idBits.clearFirstMarkedBit();
1638 const Pointer& pointer = pointerForId(id);
1639 x += pointer.x;
1640 y += pointer.y;
1641 }
1642 x /= count;
1643 y /= count;
1644 }
1645 *outX = x;
1646 *outY = y;
1647}
1648
1649
1650// --- CookedPointerData ---
1651
1652CookedPointerData::CookedPointerData() {
1653 clear();
1654}
1655
1656void CookedPointerData::clear() {
1657 pointerCount = 0;
1658 hoveringIdBits.clear();
1659 touchingIdBits.clear();
1660}
1661
1662void CookedPointerData::copyFrom(const CookedPointerData& other) {
1663 pointerCount = other.pointerCount;
1664 hoveringIdBits = other.hoveringIdBits;
1665 touchingIdBits = other.touchingIdBits;
1666
1667 for (uint32_t i = 0; i < pointerCount; i++) {
1668 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1669 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1670
1671 int id = pointerProperties[i].id;
1672 idToIndex[id] = other.idToIndex[id];
1673 }
1674}
1675
1676
1677// --- SingleTouchMotionAccumulator ---
1678
1679SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1680 clearAbsoluteAxes();
1681}
1682
1683void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1684 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1685 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1686 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1687 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1688 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1689 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1690 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1691}
1692
1693void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1694 mAbsX = 0;
1695 mAbsY = 0;
1696 mAbsPressure = 0;
1697 mAbsToolWidth = 0;
1698 mAbsDistance = 0;
1699 mAbsTiltX = 0;
1700 mAbsTiltY = 0;
1701}
1702
1703void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1704 if (rawEvent->type == EV_ABS) {
1705 switch (rawEvent->code) {
1706 case ABS_X:
1707 mAbsX = rawEvent->value;
1708 break;
1709 case ABS_Y:
1710 mAbsY = rawEvent->value;
1711 break;
1712 case ABS_PRESSURE:
1713 mAbsPressure = rawEvent->value;
1714 break;
1715 case ABS_TOOL_WIDTH:
1716 mAbsToolWidth = rawEvent->value;
1717 break;
1718 case ABS_DISTANCE:
1719 mAbsDistance = rawEvent->value;
1720 break;
1721 case ABS_TILT_X:
1722 mAbsTiltX = rawEvent->value;
1723 break;
1724 case ABS_TILT_Y:
1725 mAbsTiltY = rawEvent->value;
1726 break;
1727 }
1728 }
1729}
1730
1731
1732// --- MultiTouchMotionAccumulator ---
1733
Atif Niyaz21da0ff2019-06-28 13:22:51 -07001734MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1735 : mCurrentSlot(-1),
1736 mSlots(nullptr),
1737 mSlotCount(0),
1738 mUsingSlotsProtocol(false),
1739 mHaveStylus(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001740
1741MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1742 delete[] mSlots;
1743}
1744
1745void MultiTouchMotionAccumulator::configure(InputDevice* device,
1746 size_t slotCount, bool usingSlotsProtocol) {
1747 mSlotCount = slotCount;
1748 mUsingSlotsProtocol = usingSlotsProtocol;
1749 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1750
1751 delete[] mSlots;
1752 mSlots = new Slot[slotCount];
1753}
1754
1755void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1756 // Unfortunately there is no way to read the initial contents of the slots.
1757 // So when we reset the accumulator, we must assume they are all zeroes.
1758 if (mUsingSlotsProtocol) {
1759 // Query the driver for the current slot index and use it as the initial slot
1760 // before we start reading events from the device. It is possible that the
1761 // current slot index will not be the same as it was when the first event was
1762 // written into the evdev buffer, which means the input mapper could start
1763 // out of sync with the initial state of the events in the evdev buffer.
1764 // In the extremely unlikely case that this happens, the data from
1765 // two slots will be confused until the next ABS_MT_SLOT event is received.
1766 // This can cause the touch point to "jump", but at least there will be
1767 // no stuck touches.
1768 int32_t initialSlot;
1769 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1770 ABS_MT_SLOT, &initialSlot);
1771 if (status) {
1772 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1773 initialSlot = -1;
1774 }
1775 clearSlots(initialSlot);
1776 } else {
1777 clearSlots(-1);
1778 }
1779}
1780
1781void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1782 if (mSlots) {
1783 for (size_t i = 0; i < mSlotCount; i++) {
1784 mSlots[i].clear();
1785 }
1786 }
1787 mCurrentSlot = initialSlot;
1788}
1789
1790void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1791 if (rawEvent->type == EV_ABS) {
1792 bool newSlot = false;
1793 if (mUsingSlotsProtocol) {
1794 if (rawEvent->code == ABS_MT_SLOT) {
1795 mCurrentSlot = rawEvent->value;
1796 newSlot = true;
1797 }
1798 } else if (mCurrentSlot < 0) {
1799 mCurrentSlot = 0;
1800 }
1801
1802 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1803#if DEBUG_POINTERS
1804 if (newSlot) {
1805 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001806 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001807 mCurrentSlot, mSlotCount - 1);
1808 }
1809#endif
1810 } else {
1811 Slot* slot = &mSlots[mCurrentSlot];
1812
1813 switch (rawEvent->code) {
1814 case ABS_MT_POSITION_X:
1815 slot->mInUse = true;
1816 slot->mAbsMTPositionX = rawEvent->value;
1817 break;
1818 case ABS_MT_POSITION_Y:
1819 slot->mInUse = true;
1820 slot->mAbsMTPositionY = rawEvent->value;
1821 break;
1822 case ABS_MT_TOUCH_MAJOR:
1823 slot->mInUse = true;
1824 slot->mAbsMTTouchMajor = rawEvent->value;
1825 break;
1826 case ABS_MT_TOUCH_MINOR:
1827 slot->mInUse = true;
1828 slot->mAbsMTTouchMinor = rawEvent->value;
1829 slot->mHaveAbsMTTouchMinor = true;
1830 break;
1831 case ABS_MT_WIDTH_MAJOR:
1832 slot->mInUse = true;
1833 slot->mAbsMTWidthMajor = rawEvent->value;
1834 break;
1835 case ABS_MT_WIDTH_MINOR:
1836 slot->mInUse = true;
1837 slot->mAbsMTWidthMinor = rawEvent->value;
1838 slot->mHaveAbsMTWidthMinor = true;
1839 break;
1840 case ABS_MT_ORIENTATION:
1841 slot->mInUse = true;
1842 slot->mAbsMTOrientation = rawEvent->value;
1843 break;
1844 case ABS_MT_TRACKING_ID:
1845 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1846 // The slot is no longer in use but it retains its previous contents,
1847 // which may be reused for subsequent touches.
1848 slot->mInUse = false;
1849 } else {
1850 slot->mInUse = true;
1851 slot->mAbsMTTrackingId = rawEvent->value;
1852 }
1853 break;
1854 case ABS_MT_PRESSURE:
1855 slot->mInUse = true;
1856 slot->mAbsMTPressure = rawEvent->value;
1857 break;
1858 case ABS_MT_DISTANCE:
1859 slot->mInUse = true;
1860 slot->mAbsMTDistance = rawEvent->value;
1861 break;
1862 case ABS_MT_TOOL_TYPE:
1863 slot->mInUse = true;
1864 slot->mAbsMTToolType = rawEvent->value;
1865 slot->mHaveAbsMTToolType = true;
1866 break;
1867 }
1868 }
1869 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1870 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1871 mCurrentSlot += 1;
1872 }
1873}
1874
1875void MultiTouchMotionAccumulator::finishSync() {
1876 if (!mUsingSlotsProtocol) {
1877 clearSlots(-1);
1878 }
1879}
1880
1881bool MultiTouchMotionAccumulator::hasStylus() const {
1882 return mHaveStylus;
1883}
1884
1885
1886// --- MultiTouchMotionAccumulator::Slot ---
1887
1888MultiTouchMotionAccumulator::Slot::Slot() {
1889 clear();
1890}
1891
1892void MultiTouchMotionAccumulator::Slot::clear() {
1893 mInUse = false;
1894 mHaveAbsMTTouchMinor = false;
1895 mHaveAbsMTWidthMinor = false;
1896 mHaveAbsMTToolType = false;
1897 mAbsMTPositionX = 0;
1898 mAbsMTPositionY = 0;
1899 mAbsMTTouchMajor = 0;
1900 mAbsMTTouchMinor = 0;
1901 mAbsMTWidthMajor = 0;
1902 mAbsMTWidthMinor = 0;
1903 mAbsMTOrientation = 0;
1904 mAbsMTTrackingId = -1;
1905 mAbsMTPressure = 0;
1906 mAbsMTDistance = 0;
1907 mAbsMTToolType = 0;
1908}
1909
1910int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1911 if (mHaveAbsMTToolType) {
1912 switch (mAbsMTToolType) {
1913 case MT_TOOL_FINGER:
1914 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1915 case MT_TOOL_PEN:
1916 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1917 }
1918 }
1919 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1920}
1921
1922
1923// --- InputMapper ---
1924
1925InputMapper::InputMapper(InputDevice* device) :
1926 mDevice(device), mContext(device->getContext()) {
1927}
1928
1929InputMapper::~InputMapper() {
1930}
1931
1932void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1933 info->addSource(getSources());
1934}
1935
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001936void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001937}
1938
1939void InputMapper::configure(nsecs_t when,
1940 const InputReaderConfiguration* config, uint32_t changes) {
1941}
1942
1943void InputMapper::reset(nsecs_t when) {
1944}
1945
1946void InputMapper::timeoutExpired(nsecs_t when) {
1947}
1948
1949int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1950 return AKEY_STATE_UNKNOWN;
1951}
1952
1953int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1954 return AKEY_STATE_UNKNOWN;
1955}
1956
1957int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1958 return AKEY_STATE_UNKNOWN;
1959}
1960
1961bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1962 const int32_t* keyCodes, uint8_t* outFlags) {
1963 return false;
1964}
1965
1966void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1967 int32_t token) {
1968}
1969
1970void InputMapper::cancelVibrate(int32_t token) {
1971}
1972
Jeff Brownc9aa6282015-02-11 19:03:28 -08001973void InputMapper::cancelTouch(nsecs_t when) {
1974}
1975
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976int32_t InputMapper::getMetaState() {
1977 return 0;
1978}
1979
Andrii Kulian763a3a42016-03-08 10:46:16 -08001980void InputMapper::updateMetaState(int32_t keyCode) {
1981}
1982
Michael Wright842500e2015-03-13 17:32:02 -07001983void InputMapper::updateExternalStylusState(const StylusState& state) {
1984
1985}
1986
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987void InputMapper::fadePointer() {
1988}
1989
1990status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1991 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1992}
1993
1994void InputMapper::bumpGeneration() {
1995 mDevice->bumpGeneration();
1996}
1997
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001998void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001999 const RawAbsoluteAxisInfo& axis, const char* name) {
2000 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002001 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2003 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002004 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 }
2006}
2007
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002008void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2009 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2010 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2011 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2012 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002013}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002014
2015// --- SwitchInputMapper ---
2016
2017SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002018 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002019}
2020
2021SwitchInputMapper::~SwitchInputMapper() {
2022}
2023
2024uint32_t SwitchInputMapper::getSources() {
2025 return AINPUT_SOURCE_SWITCH;
2026}
2027
2028void SwitchInputMapper::process(const RawEvent* rawEvent) {
2029 switch (rawEvent->type) {
2030 case EV_SW:
2031 processSwitch(rawEvent->code, rawEvent->value);
2032 break;
2033
2034 case EV_SYN:
2035 if (rawEvent->code == SYN_REPORT) {
2036 sync(rawEvent->when);
2037 }
2038 }
2039}
2040
2041void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2042 if (switchCode >= 0 && switchCode < 32) {
2043 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002044 mSwitchValues |= 1 << switchCode;
2045 } else {
2046 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 }
2048 mUpdatedSwitchMask |= 1 << switchCode;
2049 }
2050}
2051
2052void SwitchInputMapper::sync(nsecs_t when) {
2053 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002054 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002055 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2056 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002057 getListener()->notifySwitch(&args);
2058
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059 mUpdatedSwitchMask = 0;
2060 }
2061}
2062
2063int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2064 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2065}
2066
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002067void SwitchInputMapper::dump(std::string& dump) {
2068 dump += INDENT2 "Switch Input Mapper:\n";
2069 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002070}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002071
2072// --- VibratorInputMapper ---
2073
2074VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2075 InputMapper(device), mVibrating(false) {
2076}
2077
2078VibratorInputMapper::~VibratorInputMapper() {
2079}
2080
2081uint32_t VibratorInputMapper::getSources() {
2082 return 0;
2083}
2084
2085void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2086 InputMapper::populateDeviceInfo(info);
2087
2088 info->setVibrator(true);
2089}
2090
2091void VibratorInputMapper::process(const RawEvent* rawEvent) {
2092 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2093}
2094
2095void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2096 int32_t token) {
2097#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002098 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099 for (size_t i = 0; i < patternSize; i++) {
2100 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002101 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002102 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002103 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002104 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002105 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002106 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002107#endif
2108
2109 mVibrating = true;
2110 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2111 mPatternSize = patternSize;
2112 mRepeat = repeat;
2113 mToken = token;
2114 mIndex = -1;
2115
2116 nextStep();
2117}
2118
2119void VibratorInputMapper::cancelVibrate(int32_t token) {
2120#if DEBUG_VIBRATOR
2121 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2122#endif
2123
2124 if (mVibrating && mToken == token) {
2125 stopVibrating();
2126 }
2127}
2128
2129void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2130 if (mVibrating) {
2131 if (when >= mNextStepTime) {
2132 nextStep();
2133 } else {
2134 getContext()->requestTimeoutAtTime(mNextStepTime);
2135 }
2136 }
2137}
2138
2139void VibratorInputMapper::nextStep() {
2140 mIndex += 1;
2141 if (size_t(mIndex) >= mPatternSize) {
2142 if (mRepeat < 0) {
2143 // We are done.
2144 stopVibrating();
2145 return;
2146 }
2147 mIndex = mRepeat;
2148 }
2149
2150 bool vibratorOn = mIndex & 1;
2151 nsecs_t duration = mPattern[mIndex];
2152 if (vibratorOn) {
2153#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002154 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155#endif
2156 getEventHub()->vibrate(getDeviceId(), duration);
2157 } else {
2158#if DEBUG_VIBRATOR
2159 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2160#endif
2161 getEventHub()->cancelVibrate(getDeviceId());
2162 }
2163 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2164 mNextStepTime = now + duration;
2165 getContext()->requestTimeoutAtTime(mNextStepTime);
2166#if DEBUG_VIBRATOR
2167 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2168#endif
2169}
2170
2171void VibratorInputMapper::stopVibrating() {
2172 mVibrating = false;
2173#if DEBUG_VIBRATOR
2174 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2175#endif
2176 getEventHub()->cancelVibrate(getDeviceId());
2177}
2178
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002179void VibratorInputMapper::dump(std::string& dump) {
2180 dump += INDENT2 "Vibrator Input Mapper:\n";
2181 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182}
2183
2184
2185// --- KeyboardInputMapper ---
2186
2187KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2188 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002189 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002190}
2191
2192KeyboardInputMapper::~KeyboardInputMapper() {
2193}
2194
2195uint32_t KeyboardInputMapper::getSources() {
2196 return mSource;
2197}
2198
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002199int32_t KeyboardInputMapper::getOrientation() {
2200 if (mViewport) {
2201 return mViewport->orientation;
2202 }
2203 return DISPLAY_ORIENTATION_0;
2204}
2205
2206int32_t KeyboardInputMapper::getDisplayId() {
2207 if (mViewport) {
2208 return mViewport->displayId;
2209 }
2210 return ADISPLAY_ID_NONE;
2211}
2212
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2214 InputMapper::populateDeviceInfo(info);
2215
2216 info->setKeyboardType(mKeyboardType);
2217 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2218}
2219
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002220void KeyboardInputMapper::dump(std::string& dump) {
2221 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002223 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002224 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002225 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2226 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2227 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228}
2229
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230void KeyboardInputMapper::configure(nsecs_t when,
2231 const InputReaderConfiguration* config, uint32_t changes) {
2232 InputMapper::configure(when, config, changes);
2233
2234 if (!changes) { // first time only
2235 // Configure basic parameters.
2236 configureParameters();
2237 }
2238
2239 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002240 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002241 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002242 }
2243 }
2244}
2245
Ivan Podogovb9afef32017-02-13 15:34:32 +00002246static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2247 int32_t mapped = 0;
2248 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2249 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2250 if (stemKeyRotationMap[i][0] == keyCode) {
2251 stemKeyRotationMap[i][1] = mapped;
2252 return;
2253 }
2254 }
2255 }
2256}
2257
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258void KeyboardInputMapper::configureParameters() {
2259 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002260 const PropertyMap& config = getDevice()->getConfiguration();
2261 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262 mParameters.orientationAware);
2263
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002265 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2266 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2267 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2268 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002270
2271 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002272 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002273 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274}
2275
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002276void KeyboardInputMapper::dumpParameters(std::string& dump) {
2277 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002278 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002279 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002280 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002281 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002282}
2283
2284void KeyboardInputMapper::reset(nsecs_t when) {
2285 mMetaState = AMETA_NONE;
2286 mDownTime = 0;
2287 mKeyDowns.clear();
2288 mCurrentHidUsage = 0;
2289
2290 resetLedState();
2291
2292 InputMapper::reset(when);
2293}
2294
2295void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2296 switch (rawEvent->type) {
2297 case EV_KEY: {
2298 int32_t scanCode = rawEvent->code;
2299 int32_t usageCode = mCurrentHidUsage;
2300 mCurrentHidUsage = 0;
2301
2302 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002303 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002304 }
2305 break;
2306 }
2307 case EV_MSC: {
2308 if (rawEvent->code == MSC_SCAN) {
2309 mCurrentHidUsage = rawEvent->value;
2310 }
2311 break;
2312 }
2313 case EV_SYN: {
2314 if (rawEvent->code == SYN_REPORT) {
2315 mCurrentHidUsage = 0;
2316 }
2317 }
2318 }
2319}
2320
2321bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2322 return scanCode < BTN_MOUSE
2323 || scanCode >= KEY_OK
2324 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2325 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2326}
2327
Michael Wright58ba9882017-07-26 16:19:11 +01002328bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2329 switch (keyCode) {
2330 case AKEYCODE_MEDIA_PLAY:
2331 case AKEYCODE_MEDIA_PAUSE:
2332 case AKEYCODE_MEDIA_PLAY_PAUSE:
2333 case AKEYCODE_MUTE:
2334 case AKEYCODE_HEADSETHOOK:
2335 case AKEYCODE_MEDIA_STOP:
2336 case AKEYCODE_MEDIA_NEXT:
2337 case AKEYCODE_MEDIA_PREVIOUS:
2338 case AKEYCODE_MEDIA_REWIND:
2339 case AKEYCODE_MEDIA_RECORD:
2340 case AKEYCODE_MEDIA_FAST_FORWARD:
2341 case AKEYCODE_MEDIA_SKIP_FORWARD:
2342 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2343 case AKEYCODE_MEDIA_STEP_FORWARD:
2344 case AKEYCODE_MEDIA_STEP_BACKWARD:
2345 case AKEYCODE_MEDIA_AUDIO_TRACK:
2346 case AKEYCODE_VOLUME_UP:
2347 case AKEYCODE_VOLUME_DOWN:
2348 case AKEYCODE_VOLUME_MUTE:
2349 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2350 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2351 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2352 return true;
2353 }
2354 return false;
2355}
2356
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002357void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2358 int32_t usageCode) {
2359 int32_t keyCode;
2360 int32_t keyMetaState;
2361 uint32_t policyFlags;
2362
2363 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2364 &keyCode, &keyMetaState, &policyFlags)) {
2365 keyCode = AKEYCODE_UNKNOWN;
2366 keyMetaState = mMetaState;
2367 policyFlags = 0;
2368 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002369
2370 if (down) {
2371 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002372 if (mParameters.orientationAware) {
2373 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002374 }
2375
2376 // Add key down.
2377 ssize_t keyDownIndex = findKeyDown(scanCode);
2378 if (keyDownIndex >= 0) {
2379 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002380 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002381 } else {
2382 // key down
2383 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2384 && mContext->shouldDropVirtualKey(when,
2385 getDevice(), keyCode, scanCode)) {
2386 return;
2387 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002388 if (policyFlags & POLICY_FLAG_GESTURE) {
2389 mDevice->cancelTouch(when);
2390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002392 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002393 keyDown.keyCode = keyCode;
2394 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002395 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 }
2397
2398 mDownTime = when;
2399 } else {
2400 // Remove key down.
2401 ssize_t keyDownIndex = findKeyDown(scanCode);
2402 if (keyDownIndex >= 0) {
2403 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002404 keyCode = mKeyDowns[keyDownIndex].keyCode;
2405 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 } else {
2407 // key was not actually down
2408 ALOGI("Dropping key up from device %s because the key was not down. "
2409 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002410 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002411 return;
2412 }
2413 }
2414
Andrii Kulian763a3a42016-03-08 10:46:16 -08002415 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002416 // If global meta state changed send it along with the key.
2417 // If it has not changed then we'll use what keymap gave us,
2418 // since key replacement logic might temporarily reset a few
2419 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002420 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422
2423 nsecs_t downTime = mDownTime;
2424
2425 // Key down on external an keyboard should wake the device.
2426 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2427 // For internal keyboards, the key layout file should specify the policy flags for
2428 // each wake key individually.
2429 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002430 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002431 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002432 }
2433
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002434 if (mParameters.handlesKeyRepeat) {
2435 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2436 }
2437
Prabir Pradhan42611e02018-11-27 14:04:02 -08002438 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2439 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002440 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002441 getListener()->notifyKey(&args);
2442}
2443
2444ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2445 size_t n = mKeyDowns.size();
2446 for (size_t i = 0; i < n; i++) {
2447 if (mKeyDowns[i].scanCode == scanCode) {
2448 return i;
2449 }
2450 }
2451 return -1;
2452}
2453
2454int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2455 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2456}
2457
2458int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2459 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2460}
2461
2462bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2463 const int32_t* keyCodes, uint8_t* outFlags) {
2464 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2465}
2466
2467int32_t KeyboardInputMapper::getMetaState() {
2468 return mMetaState;
2469}
2470
Andrii Kulian763a3a42016-03-08 10:46:16 -08002471void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2472 updateMetaStateIfNeeded(keyCode, false);
2473}
2474
2475bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2476 int32_t oldMetaState = mMetaState;
2477 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2478 bool metaStateChanged = oldMetaState != newMetaState;
2479 if (metaStateChanged) {
2480 mMetaState = newMetaState;
2481 updateLedState(false);
2482
2483 getContext()->updateGlobalMetaState();
2484 }
2485
2486 return metaStateChanged;
2487}
2488
Michael Wrightd02c5b62014-02-10 15:10:22 -08002489void KeyboardInputMapper::resetLedState() {
2490 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2491 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2492 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2493
2494 updateLedState(true);
2495}
2496
2497void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2498 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2499 ledState.on = false;
2500}
2501
2502void KeyboardInputMapper::updateLedState(bool reset) {
2503 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2504 AMETA_CAPS_LOCK_ON, reset);
2505 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2506 AMETA_NUM_LOCK_ON, reset);
2507 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2508 AMETA_SCROLL_LOCK_ON, reset);
2509}
2510
2511void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2512 int32_t led, int32_t modifier, bool reset) {
2513 if (ledState.avail) {
2514 bool desiredState = (mMetaState & modifier) != 0;
2515 if (reset || ledState.on != desiredState) {
2516 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2517 ledState.on = desiredState;
2518 }
2519 }
2520}
2521
2522
2523// --- CursorInputMapper ---
2524
2525CursorInputMapper::CursorInputMapper(InputDevice* device) :
2526 InputMapper(device) {
2527}
2528
2529CursorInputMapper::~CursorInputMapper() {
2530}
2531
2532uint32_t CursorInputMapper::getSources() {
2533 return mSource;
2534}
2535
2536void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2537 InputMapper::populateDeviceInfo(info);
2538
2539 if (mParameters.mode == Parameters::MODE_POINTER) {
2540 float minX, minY, maxX, maxY;
2541 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2542 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2543 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2544 }
2545 } else {
2546 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2547 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2548 }
2549 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2550
2551 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2552 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2553 }
2554 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2555 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2556 }
2557}
2558
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002559void CursorInputMapper::dump(std::string& dump) {
2560 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002562 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2563 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2564 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2565 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2566 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002568 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002569 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002570 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2571 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2572 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2573 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2574 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2575 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002576}
2577
2578void CursorInputMapper::configure(nsecs_t when,
2579 const InputReaderConfiguration* config, uint32_t changes) {
2580 InputMapper::configure(when, config, changes);
2581
2582 if (!changes) { // first time only
2583 mCursorScrollAccumulator.configure(getDevice());
2584
2585 // Configure basic parameters.
2586 configureParameters();
2587
2588 // Configure device mode.
2589 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002590 case Parameters::MODE_POINTER_RELATIVE:
2591 // Should not happen during first time configuration.
2592 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2593 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002594 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 case Parameters::MODE_POINTER:
2596 mSource = AINPUT_SOURCE_MOUSE;
2597 mXPrecision = 1.0f;
2598 mYPrecision = 1.0f;
2599 mXScale = 1.0f;
2600 mYScale = 1.0f;
2601 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2602 break;
2603 case Parameters::MODE_NAVIGATION:
2604 mSource = AINPUT_SOURCE_TRACKBALL;
2605 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2606 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2607 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2608 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2609 break;
2610 }
2611
2612 mVWheelScale = 1.0f;
2613 mHWheelScale = 1.0f;
2614 }
2615
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002616 if ((!changes && config->pointerCapture)
2617 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2618 if (config->pointerCapture) {
2619 if (mParameters.mode == Parameters::MODE_POINTER) {
2620 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2621 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2622 // Keep PointerController around in order to preserve the pointer position.
2623 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2624 } else {
2625 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2626 }
2627 } else {
2628 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2629 mParameters.mode = Parameters::MODE_POINTER;
2630 mSource = AINPUT_SOURCE_MOUSE;
2631 } else {
2632 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2633 }
2634 }
2635 bumpGeneration();
2636 if (changes) {
2637 getDevice()->notifyReset(when);
2638 }
2639 }
2640
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2642 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2643 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2644 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2645 }
2646
2647 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002648 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002650 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002651 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002652 if (internalViewport) {
2653 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002656
2657 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002658 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002659 getPolicy()->obtainPointerController(getDeviceId());
2660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 bumpGeneration();
2662 }
2663}
2664
2665void CursorInputMapper::configureParameters() {
2666 mParameters.mode = Parameters::MODE_POINTER;
2667 String8 cursorModeString;
2668 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2669 if (cursorModeString == "navigation") {
2670 mParameters.mode = Parameters::MODE_NAVIGATION;
2671 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2672 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2673 }
2674 }
2675
2676 mParameters.orientationAware = false;
2677 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2678 mParameters.orientationAware);
2679
2680 mParameters.hasAssociatedDisplay = false;
2681 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2682 mParameters.hasAssociatedDisplay = true;
2683 }
2684}
2685
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002686void CursorInputMapper::dumpParameters(std::string& dump) {
2687 dump += INDENT3 "Parameters:\n";
2688 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 toString(mParameters.hasAssociatedDisplay));
2690
2691 switch (mParameters.mode) {
2692 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002693 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002695 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002696 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002697 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002699 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 break;
2701 default:
2702 ALOG_ASSERT(false);
2703 }
2704
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002705 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 toString(mParameters.orientationAware));
2707}
2708
2709void CursorInputMapper::reset(nsecs_t when) {
2710 mButtonState = 0;
2711 mDownTime = 0;
2712
2713 mPointerVelocityControl.reset();
2714 mWheelXVelocityControl.reset();
2715 mWheelYVelocityControl.reset();
2716
2717 mCursorButtonAccumulator.reset(getDevice());
2718 mCursorMotionAccumulator.reset(getDevice());
2719 mCursorScrollAccumulator.reset(getDevice());
2720
2721 InputMapper::reset(when);
2722}
2723
2724void CursorInputMapper::process(const RawEvent* rawEvent) {
2725 mCursorButtonAccumulator.process(rawEvent);
2726 mCursorMotionAccumulator.process(rawEvent);
2727 mCursorScrollAccumulator.process(rawEvent);
2728
2729 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2730 sync(rawEvent->when);
2731 }
2732}
2733
2734void CursorInputMapper::sync(nsecs_t when) {
2735 int32_t lastButtonState = mButtonState;
2736 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2737 mButtonState = currentButtonState;
2738
2739 bool wasDown = isPointerDown(lastButtonState);
2740 bool down = isPointerDown(currentButtonState);
2741 bool downChanged;
2742 if (!wasDown && down) {
2743 mDownTime = when;
2744 downChanged = true;
2745 } else if (wasDown && !down) {
2746 downChanged = true;
2747 } else {
2748 downChanged = false;
2749 }
2750 nsecs_t downTime = mDownTime;
2751 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002752 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2753 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002754
2755 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2756 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2757 bool moved = deltaX != 0 || deltaY != 0;
2758
2759 // Rotate delta according to orientation if needed.
2760 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2761 && (deltaX != 0.0f || deltaY != 0.0f)) {
2762 rotateDelta(mOrientation, &deltaX, &deltaY);
2763 }
2764
2765 // Move the pointer.
2766 PointerProperties pointerProperties;
2767 pointerProperties.clear();
2768 pointerProperties.id = 0;
2769 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2770
2771 PointerCoords pointerCoords;
2772 pointerCoords.clear();
2773
2774 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2775 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2776 bool scrolled = vscroll != 0 || hscroll != 0;
2777
Yi Kong9b14ac62018-07-17 13:48:38 -07002778 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2779 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002780
2781 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2782
2783 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002784 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2785 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002786 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787 if (moved || scrolled || buttonsChanged) {
2788 mPointerController->setPresentation(
2789 PointerControllerInterface::PRESENTATION_POINTER);
2790
2791 if (moved) {
2792 mPointerController->move(deltaX, deltaY);
2793 }
2794
2795 if (buttonsChanged) {
2796 mPointerController->setButtonState(currentButtonState);
2797 }
2798
2799 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2800 }
2801
Garfield Tan00f511d2019-06-12 16:55:40 -07002802 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2803 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2804 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2806 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002807 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808 } else {
2809 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2811 displayId = ADISPLAY_ID_NONE;
2812 }
2813
2814 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2815
2816 // Moving an external trackball or mouse should wake the device.
2817 // We don't do this for internal cursor devices to prevent them from waking up
2818 // the device in your pocket.
2819 // TODO: Use the input device configuration to control this behavior more finely.
2820 uint32_t policyFlags = 0;
2821 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002822 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002823 }
2824
2825 // Synthesize key down from buttons if needed.
2826 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002827 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828
2829 // Send motion event.
2830 if (downChanged || moved || scrolled || buttonsChanged) {
2831 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002832 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002833 int32_t motionEventAction;
2834 if (downChanged) {
2835 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002836 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2838 } else {
2839 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2840 }
2841
Michael Wright7b159c92015-05-14 14:48:03 +01002842 if (buttonsReleased) {
2843 BitSet32 released(buttonsReleased);
2844 while (!released.isEmpty()) {
2845 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2846 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002847 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002848 mSource, displayId, policyFlags,
2849 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2850 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002851 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002852 &pointerCoords, mXPrecision, mYPrecision,
2853 xCursorPosition, yCursorPosition, downTime,
2854 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002855 getListener()->notifyMotion(&releaseArgs);
2856 }
2857 }
2858
Prabir Pradhan42611e02018-11-27 14:04:02 -08002859 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Garfield Tan00f511d2019-06-12 16:55:40 -07002860 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2861 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002862 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
Garfield Tan00f511d2019-06-12 16:55:40 -07002863 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2864 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 getListener()->notifyMotion(&args);
2866
Michael Wright7b159c92015-05-14 14:48:03 +01002867 if (buttonsPressed) {
2868 BitSet32 pressed(buttonsPressed);
2869 while (!pressed.isEmpty()) {
2870 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2871 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002872 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002873 mSource, displayId, policyFlags,
2874 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2875 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002876 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002877 &pointerCoords, mXPrecision, mYPrecision,
2878 xCursorPosition, yCursorPosition, downTime,
2879 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002880 getListener()->notifyMotion(&pressArgs);
2881 }
2882 }
2883
2884 ALOG_ASSERT(buttonState == currentButtonState);
2885
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886 // Send hover move after UP to tell the application that the mouse is hovering now.
2887 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002888 && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002889 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2890 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2891 0, metaState, currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002892 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002893 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002894 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002895 getListener()->notifyMotion(&hoverArgs);
2896 }
2897
2898 // Send scroll events.
2899 if (scrolled) {
2900 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2901 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2902
Prabir Pradhan42611e02018-11-27 14:04:02 -08002903 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002904 mSource, displayId, policyFlags,
2905 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2906 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002907 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002908 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002909 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002910 getListener()->notifyMotion(&scrollArgs);
2911 }
2912 }
2913
2914 // Synthesize key up from buttons if needed.
2915 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002916 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002917
2918 mCursorMotionAccumulator.finishSync();
2919 mCursorScrollAccumulator.finishSync();
2920}
2921
2922int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2923 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2924 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2925 } else {
2926 return AKEY_STATE_UNKNOWN;
2927 }
2928}
2929
2930void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002931 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2933 }
2934}
2935
Arthur Hungc23540e2018-11-29 20:42:11 +08002936std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2937 if (mParameters.hasAssociatedDisplay) {
2938 if (mParameters.mode == Parameters::MODE_POINTER) {
2939 return std::make_optional(mPointerController->getDisplayId());
2940 } else {
2941 // If the device is orientationAware and not a mouse,
2942 // it expects to dispatch events to any display
2943 return std::make_optional(ADISPLAY_ID_NONE);
2944 }
2945 }
2946 return std::nullopt;
2947}
2948
Prashant Malani1941ff52015-08-11 18:29:28 -07002949// --- RotaryEncoderInputMapper ---
2950
2951RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002952 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002953 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2954}
2955
2956RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2957}
2958
2959uint32_t RotaryEncoderInputMapper::getSources() {
2960 return mSource;
2961}
2962
2963void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2964 InputMapper::populateDeviceInfo(info);
2965
2966 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002967 float res = 0.0f;
2968 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2969 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2970 }
2971 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2972 mScalingFactor)) {
2973 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2974 "default to 1.0!\n");
2975 mScalingFactor = 1.0f;
2976 }
2977 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2978 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002979 }
2980}
2981
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002982void RotaryEncoderInputMapper::dump(std::string& dump) {
2983 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2984 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002985 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2986}
2987
2988void RotaryEncoderInputMapper::configure(nsecs_t when,
2989 const InputReaderConfiguration* config, uint32_t changes) {
2990 InputMapper::configure(when, config, changes);
2991 if (!changes) {
2992 mRotaryEncoderScrollAccumulator.configure(getDevice());
2993 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002994 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002995 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002996 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002997 if (internalViewport) {
2998 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002999 } else {
3000 mOrientation = DISPLAY_ORIENTATION_0;
3001 }
3002 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003003}
3004
3005void RotaryEncoderInputMapper::reset(nsecs_t when) {
3006 mRotaryEncoderScrollAccumulator.reset(getDevice());
3007
3008 InputMapper::reset(when);
3009}
3010
3011void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3012 mRotaryEncoderScrollAccumulator.process(rawEvent);
3013
3014 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3015 sync(rawEvent->when);
3016 }
3017}
3018
3019void RotaryEncoderInputMapper::sync(nsecs_t when) {
3020 PointerCoords pointerCoords;
3021 pointerCoords.clear();
3022
3023 PointerProperties pointerProperties;
3024 pointerProperties.clear();
3025 pointerProperties.id = 0;
3026 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3027
3028 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3029 bool scrolled = scroll != 0;
3030
3031 // This is not a pointer, so it's not associated with a display.
3032 int32_t displayId = ADISPLAY_ID_NONE;
3033
3034 // Moving the rotary encoder should wake the device (if specified).
3035 uint32_t policyFlags = 0;
3036 if (scrolled && getDevice()->isExternal()) {
3037 policyFlags |= POLICY_FLAG_WAKE;
3038 }
3039
Ivan Podogovad437252016-09-29 16:29:55 +01003040 if (mOrientation == DISPLAY_ORIENTATION_180) {
3041 scroll = -scroll;
3042 }
3043
Prashant Malani1941ff52015-08-11 18:29:28 -07003044 // Send motion event.
3045 if (scrolled) {
3046 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003047 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003048
Garfield Tan00f511d2019-06-12 16:55:40 -07003049 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3050 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3051 metaState, /* buttonState */ 0, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07003052 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
3053 &pointerCoords, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Garfield Tan00f511d2019-06-12 16:55:40 -07003054 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003055 getListener()->notifyMotion(&scrollArgs);
3056 }
3057
3058 mRotaryEncoderScrollAccumulator.finishSync();
3059}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003060
3061// --- TouchInputMapper ---
3062
3063TouchInputMapper::TouchInputMapper(InputDevice* device) :
3064 InputMapper(device),
3065 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3066 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003067 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003068 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3069}
3070
3071TouchInputMapper::~TouchInputMapper() {
3072}
3073
3074uint32_t TouchInputMapper::getSources() {
3075 return mSource;
3076}
3077
3078void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3079 InputMapper::populateDeviceInfo(info);
3080
3081 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3082 info->addMotionRange(mOrientedRanges.x);
3083 info->addMotionRange(mOrientedRanges.y);
3084 info->addMotionRange(mOrientedRanges.pressure);
3085
3086 if (mOrientedRanges.haveSize) {
3087 info->addMotionRange(mOrientedRanges.size);
3088 }
3089
3090 if (mOrientedRanges.haveTouchSize) {
3091 info->addMotionRange(mOrientedRanges.touchMajor);
3092 info->addMotionRange(mOrientedRanges.touchMinor);
3093 }
3094
3095 if (mOrientedRanges.haveToolSize) {
3096 info->addMotionRange(mOrientedRanges.toolMajor);
3097 info->addMotionRange(mOrientedRanges.toolMinor);
3098 }
3099
3100 if (mOrientedRanges.haveOrientation) {
3101 info->addMotionRange(mOrientedRanges.orientation);
3102 }
3103
3104 if (mOrientedRanges.haveDistance) {
3105 info->addMotionRange(mOrientedRanges.distance);
3106 }
3107
3108 if (mOrientedRanges.haveTilt) {
3109 info->addMotionRange(mOrientedRanges.tilt);
3110 }
3111
3112 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3113 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3114 0.0f);
3115 }
3116 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3117 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3118 0.0f);
3119 }
3120 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3121 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3122 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3123 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3124 x.fuzz, x.resolution);
3125 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3126 y.fuzz, y.resolution);
3127 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3128 x.fuzz, x.resolution);
3129 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3130 y.fuzz, y.resolution);
3131 }
3132 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3133 }
3134}
3135
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003136void TouchInputMapper::dump(std::string& dump) {
3137 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 dumpParameters(dump);
3139 dumpVirtualKeys(dump);
3140 dumpRawPointerAxes(dump);
3141 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003142 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003143 dumpSurface(dump);
3144
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003145 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3146 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3147 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3148 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3149 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3150 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3151 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3152 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3153 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3154 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3155 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3156 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3157 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3158 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3159 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3160 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3161 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003162
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003163 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3164 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003165 mLastRawState.rawPointerData.pointerCount);
3166 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3167 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003168 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3170 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3171 "toolType=%d, isHovering=%s\n", i,
3172 pointer.id, pointer.x, pointer.y, pointer.pressure,
3173 pointer.touchMajor, pointer.touchMinor,
3174 pointer.toolMajor, pointer.toolMinor,
3175 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3176 pointer.toolType, toString(pointer.isHovering));
3177 }
3178
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003179 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3180 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003181 mLastCookedState.cookedPointerData.pointerCount);
3182 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3183 const PointerProperties& pointerProperties =
3184 mLastCookedState.cookedPointerData.pointerProperties[i];
3185 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003186 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3188 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3189 "toolType=%d, isHovering=%s\n", i,
3190 pointerProperties.id,
3191 pointerCoords.getX(),
3192 pointerCoords.getY(),
3193 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3194 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3195 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3196 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3197 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3198 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3199 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3200 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3201 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003202 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003203 }
3204
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003205 dump += INDENT3 "Stylus Fusion:\n";
3206 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003207 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003208 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3209 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003210 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003211 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003212 dumpStylusState(dump, mExternalStylusState);
3213
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003215 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3216 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003217 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003218 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003220 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003221 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003222 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003224 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 mPointerGestureMaxSwipeWidth);
3226 }
3227}
3228
Santos Cordonfa5cf462017-04-05 10:37:00 -07003229const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3230 switch (deviceMode) {
3231 case DEVICE_MODE_DISABLED:
3232 return "disabled";
3233 case DEVICE_MODE_DIRECT:
3234 return "direct";
3235 case DEVICE_MODE_UNSCALED:
3236 return "unscaled";
3237 case DEVICE_MODE_NAVIGATION:
3238 return "navigation";
3239 case DEVICE_MODE_POINTER:
3240 return "pointer";
3241 }
3242 return "unknown";
3243}
3244
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245void TouchInputMapper::configure(nsecs_t when,
3246 const InputReaderConfiguration* config, uint32_t changes) {
3247 InputMapper::configure(when, config, changes);
3248
3249 mConfig = *config;
3250
3251 if (!changes) { // first time only
3252 // Configure basic parameters.
3253 configureParameters();
3254
3255 // Configure common accumulators.
3256 mCursorScrollAccumulator.configure(getDevice());
3257 mTouchButtonAccumulator.configure(getDevice());
3258
3259 // Configure absolute axis information.
3260 configureRawPointerAxes();
3261
3262 // Prepare input device calibration.
3263 parseCalibration();
3264 resolveCalibration();
3265 }
3266
Michael Wright842500e2015-03-13 17:32:02 -07003267 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003268 // Update location calibration to reflect current settings
3269 updateAffineTransformation();
3270 }
3271
Michael Wrightd02c5b62014-02-10 15:10:22 -08003272 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3273 // Update pointer speed.
3274 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3275 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3276 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3277 }
3278
3279 bool resetNeeded = false;
3280 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3281 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003282 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3283 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003284 // Configure device sources, surface dimensions, orientation and
3285 // scaling factors.
3286 configureSurface(when, &resetNeeded);
3287 }
3288
3289 if (changes && resetNeeded) {
3290 // Send reset, unless this is the first time the device has been configured,
3291 // in which case the reader will call reset itself after all mappers are ready.
3292 getDevice()->notifyReset(when);
3293 }
3294}
3295
Michael Wright842500e2015-03-13 17:32:02 -07003296void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003297 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003298 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003299 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003300
3301 if (!mExternalStylusConnected) {
3302 resetExternalStylus();
3303 }
3304}
3305
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306void TouchInputMapper::configureParameters() {
3307 // Use the pointer presentation mode for devices that do not support distinct
3308 // multitouch. The spot-based presentation relies on being able to accurately
3309 // locate two or more fingers on the touch pad.
3310 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003311 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312
3313 String8 gestureModeString;
3314 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3315 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003316 if (gestureModeString == "single-touch") {
3317 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3318 } else if (gestureModeString == "multi-touch") {
3319 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320 } else if (gestureModeString != "default") {
3321 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3322 }
3323 }
3324
3325 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3326 // The device is a touch screen.
3327 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3328 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3329 // The device is a pointing device like a track pad.
3330 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3331 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3332 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3333 // The device is a cursor device with a touch pad attached.
3334 // By default don't use the touch pad to move the pointer.
3335 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3336 } else {
3337 // The device is a touch pad of unknown purpose.
3338 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3339 }
3340
3341 mParameters.hasButtonUnderPad=
3342 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3343
3344 String8 deviceTypeString;
3345 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3346 deviceTypeString)) {
3347 if (deviceTypeString == "touchScreen") {
3348 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3349 } else if (deviceTypeString == "touchPad") {
3350 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3351 } else if (deviceTypeString == "touchNavigation") {
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3353 } else if (deviceTypeString == "pointer") {
3354 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3355 } else if (deviceTypeString != "default") {
3356 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3357 }
3358 }
3359
3360 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3361 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3362 mParameters.orientationAware);
3363
3364 mParameters.hasAssociatedDisplay = false;
3365 mParameters.associatedDisplayIsExternal = false;
3366 if (mParameters.orientationAware
3367 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3368 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3369 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003370 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3371 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003372 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003373 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003374 uniqueDisplayId);
3375 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003376 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003378 if (getDevice()->getAssociatedDisplayPort()) {
3379 mParameters.hasAssociatedDisplay = true;
3380 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003381
3382 // Initial downs on external touch devices should wake the device.
3383 // Normally we don't do this for internal touch screens to prevent them from waking
3384 // up in your pocket but you can enable it using the input device configuration.
3385 mParameters.wake = getDevice()->isExternal();
3386 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3387 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388}
3389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390void TouchInputMapper::dumpParameters(std::string& dump) {
3391 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392
3393 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003394 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003395 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003397 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003398 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 break;
3400 default:
3401 assert(false);
3402 }
3403
3404 switch (mParameters.deviceType) {
3405 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003406 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003407 break;
3408 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003409 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 break;
3411 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003412 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 break;
3414 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 break;
3417 default:
3418 ALOG_ASSERT(false);
3419 }
3420
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003422 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003423 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003424 toString(mParameters.associatedDisplayIsExternal),
3425 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003426 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003427 toString(mParameters.orientationAware));
3428}
3429
3430void TouchInputMapper::configureRawPointerAxes() {
3431 mRawPointerAxes.clear();
3432}
3433
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3435 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003436 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3437 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3438 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3439 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3440 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3441 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3444 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3445 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3446 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3447 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3449}
3450
Michael Wright842500e2015-03-13 17:32:02 -07003451bool TouchInputMapper::hasExternalStylus() const {
3452 return mExternalStylusConnected;
3453}
3454
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003455/**
3456 * Determine which DisplayViewport to use.
3457 * 1. If display port is specified, return the matching viewport. If matching viewport not
3458 * found, then return.
3459 * 2. If a device has associated display, get the matching viewport by either unique id or by
3460 * the display type (internal or external).
3461 * 3. Otherwise, use a non-display viewport.
3462 */
3463std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3464 if (mParameters.hasAssociatedDisplay) {
3465 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3466 if (displayPort) {
3467 // Find the viewport that contains the same port
3468 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3469 if (!v) {
3470 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3471 "but the corresponding viewport is not found.",
3472 getDeviceName().c_str(), *displayPort);
3473 }
3474 return v;
3475 }
3476
3477 if (!mParameters.uniqueDisplayId.empty()) {
3478 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3479 }
3480
3481 ViewportType viewportTypeToUse;
3482 if (mParameters.associatedDisplayIsExternal) {
3483 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3484 } else {
3485 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3486 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003487
3488 std::optional<DisplayViewport> viewport =
3489 mConfig.getDisplayViewportByType(viewportTypeToUse);
3490 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3491 ALOGW("Input device %s should be associated with external display, "
3492 "fallback to internal one for the external viewport is not found.",
3493 getDeviceName().c_str());
3494 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3495 }
3496
3497 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003498 }
3499
3500 DisplayViewport newViewport;
3501 // Raw width and height in the natural orientation.
3502 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3503 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3504 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3505 return std::make_optional(newViewport);
3506}
3507
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3509 int32_t oldDeviceMode = mDeviceMode;
3510
Michael Wright842500e2015-03-13 17:32:02 -07003511 resolveExternalStylusPresence();
3512
Michael Wrightd02c5b62014-02-10 15:10:22 -08003513 // Determine device mode.
3514 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3515 && mConfig.pointerGesturesEnabled) {
3516 mSource = AINPUT_SOURCE_MOUSE;
3517 mDeviceMode = DEVICE_MODE_POINTER;
3518 if (hasStylus()) {
3519 mSource |= AINPUT_SOURCE_STYLUS;
3520 }
3521 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3522 && mParameters.hasAssociatedDisplay) {
3523 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3524 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003525 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 mSource |= AINPUT_SOURCE_STYLUS;
3527 }
Michael Wright2f78b682015-06-12 15:25:08 +01003528 if (hasExternalStylus()) {
3529 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3530 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3532 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3533 mDeviceMode = DEVICE_MODE_NAVIGATION;
3534 } else {
3535 mSource = AINPUT_SOURCE_TOUCHPAD;
3536 mDeviceMode = DEVICE_MODE_UNSCALED;
3537 }
3538
3539 // Ensure we have valid X and Y axes.
3540 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003541 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003542 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003543 mDeviceMode = DEVICE_MODE_DISABLED;
3544 return;
3545 }
3546
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003547 // Get associated display dimensions.
3548 std::optional<DisplayViewport> newViewport = findViewport();
3549 if (!newViewport) {
3550 ALOGI("Touch device '%s' could not query the properties of its associated "
3551 "display. The device will be inoperable until the display size "
3552 "becomes available.",
3553 getDeviceName().c_str());
3554 mDeviceMode = DEVICE_MODE_DISABLED;
3555 return;
3556 }
3557
Michael Wrightd02c5b62014-02-10 15:10:22 -08003558 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003559 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3560 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003561
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003562 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003563 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003564 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565
3566 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3567 // Convert rotated viewport to natural surface coordinates.
3568 int32_t naturalLogicalWidth, naturalLogicalHeight;
3569 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3570 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3571 int32_t naturalDeviceWidth, naturalDeviceHeight;
3572 switch (mViewport.orientation) {
3573 case DISPLAY_ORIENTATION_90:
3574 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3575 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3576 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3577 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3578 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3579 naturalPhysicalTop = mViewport.physicalLeft;
3580 naturalDeviceWidth = mViewport.deviceHeight;
3581 naturalDeviceHeight = mViewport.deviceWidth;
3582 break;
3583 case DISPLAY_ORIENTATION_180:
3584 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3585 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3586 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3587 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3588 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3589 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3590 naturalDeviceWidth = mViewport.deviceWidth;
3591 naturalDeviceHeight = mViewport.deviceHeight;
3592 break;
3593 case DISPLAY_ORIENTATION_270:
3594 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3595 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3596 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3597 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3598 naturalPhysicalLeft = mViewport.physicalTop;
3599 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3600 naturalDeviceWidth = mViewport.deviceHeight;
3601 naturalDeviceHeight = mViewport.deviceWidth;
3602 break;
3603 case DISPLAY_ORIENTATION_0:
3604 default:
3605 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3606 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3607 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3608 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3609 naturalPhysicalLeft = mViewport.physicalLeft;
3610 naturalPhysicalTop = mViewport.physicalTop;
3611 naturalDeviceWidth = mViewport.deviceWidth;
3612 naturalDeviceHeight = mViewport.deviceHeight;
3613 break;
3614 }
3615
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003616 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3617 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3618 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3619 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3620 }
3621
Michael Wright358bcc72018-08-21 04:01:07 +01003622 mPhysicalWidth = naturalPhysicalWidth;
3623 mPhysicalHeight = naturalPhysicalHeight;
3624 mPhysicalLeft = naturalPhysicalLeft;
3625 mPhysicalTop = naturalPhysicalTop;
3626
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3628 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3629 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3630 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3631
3632 mSurfaceOrientation = mParameters.orientationAware ?
3633 mViewport.orientation : DISPLAY_ORIENTATION_0;
3634 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003635 mPhysicalWidth = rawWidth;
3636 mPhysicalHeight = rawHeight;
3637 mPhysicalLeft = 0;
3638 mPhysicalTop = 0;
3639
Michael Wrightd02c5b62014-02-10 15:10:22 -08003640 mSurfaceWidth = rawWidth;
3641 mSurfaceHeight = rawHeight;
3642 mSurfaceLeft = 0;
3643 mSurfaceTop = 0;
3644 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3645 }
3646 }
3647
3648 // If moving between pointer modes, need to reset some state.
3649 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3650 if (deviceModeChanged) {
3651 mOrientedRanges.clear();
3652 }
3653
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003654 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003655 if (mDeviceMode == DEVICE_MODE_POINTER ||
3656 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003657 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003658 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3659 }
3660 } else {
3661 mPointerController.clear();
3662 }
3663
3664 if (viewportChanged || deviceModeChanged) {
3665 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3666 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003667 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003668 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3669
3670 // Configure X and Y factors.
3671 mXScale = float(mSurfaceWidth) / rawWidth;
3672 mYScale = float(mSurfaceHeight) / rawHeight;
3673 mXTranslate = -mSurfaceLeft;
3674 mYTranslate = -mSurfaceTop;
3675 mXPrecision = 1.0f / mXScale;
3676 mYPrecision = 1.0f / mYScale;
3677
3678 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3679 mOrientedRanges.x.source = mSource;
3680 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3681 mOrientedRanges.y.source = mSource;
3682
3683 configureVirtualKeys();
3684
3685 // Scale factor for terms that are not oriented in a particular axis.
3686 // If the pixels are square then xScale == yScale otherwise we fake it
3687 // by choosing an average.
3688 mGeometricScale = avg(mXScale, mYScale);
3689
3690 // Size of diagonal axis.
3691 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3692
3693 // Size factors.
3694 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3695 if (mRawPointerAxes.touchMajor.valid
3696 && mRawPointerAxes.touchMajor.maxValue != 0) {
3697 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3698 } else if (mRawPointerAxes.toolMajor.valid
3699 && mRawPointerAxes.toolMajor.maxValue != 0) {
3700 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3701 } else {
3702 mSizeScale = 0.0f;
3703 }
3704
3705 mOrientedRanges.haveTouchSize = true;
3706 mOrientedRanges.haveToolSize = true;
3707 mOrientedRanges.haveSize = true;
3708
3709 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3710 mOrientedRanges.touchMajor.source = mSource;
3711 mOrientedRanges.touchMajor.min = 0;
3712 mOrientedRanges.touchMajor.max = diagonalSize;
3713 mOrientedRanges.touchMajor.flat = 0;
3714 mOrientedRanges.touchMajor.fuzz = 0;
3715 mOrientedRanges.touchMajor.resolution = 0;
3716
3717 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3718 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3719
3720 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3721 mOrientedRanges.toolMajor.source = mSource;
3722 mOrientedRanges.toolMajor.min = 0;
3723 mOrientedRanges.toolMajor.max = diagonalSize;
3724 mOrientedRanges.toolMajor.flat = 0;
3725 mOrientedRanges.toolMajor.fuzz = 0;
3726 mOrientedRanges.toolMajor.resolution = 0;
3727
3728 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3729 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3730
3731 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3732 mOrientedRanges.size.source = mSource;
3733 mOrientedRanges.size.min = 0;
3734 mOrientedRanges.size.max = 1.0;
3735 mOrientedRanges.size.flat = 0;
3736 mOrientedRanges.size.fuzz = 0;
3737 mOrientedRanges.size.resolution = 0;
3738 } else {
3739 mSizeScale = 0.0f;
3740 }
3741
3742 // Pressure factors.
3743 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003744 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003745 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3746 || mCalibration.pressureCalibration
3747 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3748 if (mCalibration.havePressureScale) {
3749 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003750 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 } else if (mRawPointerAxes.pressure.valid
3752 && mRawPointerAxes.pressure.maxValue != 0) {
3753 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3754 }
3755 }
3756
3757 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3758 mOrientedRanges.pressure.source = mSource;
3759 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003760 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003761 mOrientedRanges.pressure.flat = 0;
3762 mOrientedRanges.pressure.fuzz = 0;
3763 mOrientedRanges.pressure.resolution = 0;
3764
3765 // Tilt
3766 mTiltXCenter = 0;
3767 mTiltXScale = 0;
3768 mTiltYCenter = 0;
3769 mTiltYScale = 0;
3770 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3771 if (mHaveTilt) {
3772 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3773 mRawPointerAxes.tiltX.maxValue);
3774 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3775 mRawPointerAxes.tiltY.maxValue);
3776 mTiltXScale = M_PI / 180;
3777 mTiltYScale = M_PI / 180;
3778
3779 mOrientedRanges.haveTilt = true;
3780
3781 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3782 mOrientedRanges.tilt.source = mSource;
3783 mOrientedRanges.tilt.min = 0;
3784 mOrientedRanges.tilt.max = M_PI_2;
3785 mOrientedRanges.tilt.flat = 0;
3786 mOrientedRanges.tilt.fuzz = 0;
3787 mOrientedRanges.tilt.resolution = 0;
3788 }
3789
3790 // Orientation
3791 mOrientationScale = 0;
3792 if (mHaveTilt) {
3793 mOrientedRanges.haveOrientation = true;
3794
3795 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3796 mOrientedRanges.orientation.source = mSource;
3797 mOrientedRanges.orientation.min = -M_PI;
3798 mOrientedRanges.orientation.max = M_PI;
3799 mOrientedRanges.orientation.flat = 0;
3800 mOrientedRanges.orientation.fuzz = 0;
3801 mOrientedRanges.orientation.resolution = 0;
3802 } else if (mCalibration.orientationCalibration !=
3803 Calibration::ORIENTATION_CALIBRATION_NONE) {
3804 if (mCalibration.orientationCalibration
3805 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3806 if (mRawPointerAxes.orientation.valid) {
3807 if (mRawPointerAxes.orientation.maxValue > 0) {
3808 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3809 } else if (mRawPointerAxes.orientation.minValue < 0) {
3810 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3811 } else {
3812 mOrientationScale = 0;
3813 }
3814 }
3815 }
3816
3817 mOrientedRanges.haveOrientation = true;
3818
3819 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3820 mOrientedRanges.orientation.source = mSource;
3821 mOrientedRanges.orientation.min = -M_PI_2;
3822 mOrientedRanges.orientation.max = M_PI_2;
3823 mOrientedRanges.orientation.flat = 0;
3824 mOrientedRanges.orientation.fuzz = 0;
3825 mOrientedRanges.orientation.resolution = 0;
3826 }
3827
3828 // Distance
3829 mDistanceScale = 0;
3830 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3831 if (mCalibration.distanceCalibration
3832 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3833 if (mCalibration.haveDistanceScale) {
3834 mDistanceScale = mCalibration.distanceScale;
3835 } else {
3836 mDistanceScale = 1.0f;
3837 }
3838 }
3839
3840 mOrientedRanges.haveDistance = true;
3841
3842 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3843 mOrientedRanges.distance.source = mSource;
3844 mOrientedRanges.distance.min =
3845 mRawPointerAxes.distance.minValue * mDistanceScale;
3846 mOrientedRanges.distance.max =
3847 mRawPointerAxes.distance.maxValue * mDistanceScale;
3848 mOrientedRanges.distance.flat = 0;
3849 mOrientedRanges.distance.fuzz =
3850 mRawPointerAxes.distance.fuzz * mDistanceScale;
3851 mOrientedRanges.distance.resolution = 0;
3852 }
3853
3854 // Compute oriented precision, scales and ranges.
3855 // Note that the maximum value reported is an inclusive maximum value so it is one
3856 // unit less than the total width or height of surface.
3857 switch (mSurfaceOrientation) {
3858 case DISPLAY_ORIENTATION_90:
3859 case DISPLAY_ORIENTATION_270:
3860 mOrientedXPrecision = mYPrecision;
3861 mOrientedYPrecision = mXPrecision;
3862
3863 mOrientedRanges.x.min = mYTranslate;
3864 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3865 mOrientedRanges.x.flat = 0;
3866 mOrientedRanges.x.fuzz = 0;
3867 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3868
3869 mOrientedRanges.y.min = mXTranslate;
3870 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3871 mOrientedRanges.y.flat = 0;
3872 mOrientedRanges.y.fuzz = 0;
3873 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3874 break;
3875
3876 default:
3877 mOrientedXPrecision = mXPrecision;
3878 mOrientedYPrecision = mYPrecision;
3879
3880 mOrientedRanges.x.min = mXTranslate;
3881 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3882 mOrientedRanges.x.flat = 0;
3883 mOrientedRanges.x.fuzz = 0;
3884 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3885
3886 mOrientedRanges.y.min = mYTranslate;
3887 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3888 mOrientedRanges.y.flat = 0;
3889 mOrientedRanges.y.fuzz = 0;
3890 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3891 break;
3892 }
3893
Jason Gerecke71b16e82014-03-10 09:47:59 -07003894 // Location
3895 updateAffineTransformation();
3896
Michael Wrightd02c5b62014-02-10 15:10:22 -08003897 if (mDeviceMode == DEVICE_MODE_POINTER) {
3898 // Compute pointer gesture detection parameters.
3899 float rawDiagonal = hypotf(rawWidth, rawHeight);
3900 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3901
3902 // Scale movements such that one whole swipe of the touch pad covers a
3903 // given area relative to the diagonal size of the display when no acceleration
3904 // is applied.
3905 // Assume that the touch pad has a square aspect ratio such that movements in
3906 // X and Y of the same number of raw units cover the same physical distance.
3907 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3908 * displayDiagonal / rawDiagonal;
3909 mPointerYMovementScale = mPointerXMovementScale;
3910
3911 // Scale zooms to cover a smaller range of the display than movements do.
3912 // This value determines the area around the pointer that is affected by freeform
3913 // pointer gestures.
3914 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3915 * displayDiagonal / rawDiagonal;
3916 mPointerYZoomScale = mPointerXZoomScale;
3917
3918 // Max width between pointers to detect a swipe gesture is more than some fraction
3919 // of the diagonal axis of the touch pad. Touches that are wider than this are
3920 // translated into freeform gestures.
3921 mPointerGestureMaxSwipeWidth =
3922 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3923
3924 // Abort current pointer usages because the state has changed.
3925 abortPointerUsage(when, 0 /*policyFlags*/);
3926 }
3927
3928 // Inform the dispatcher about the changes.
3929 *outResetNeeded = true;
3930 bumpGeneration();
3931 }
3932}
3933
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003934void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003935 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003936 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3937 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3938 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3939 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003940 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3941 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3942 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3943 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003944 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003945}
3946
3947void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003948 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3950
3951 mVirtualKeys.clear();
3952
3953 if (virtualKeyDefinitions.size() == 0) {
3954 return;
3955 }
3956
Michael Wrightd02c5b62014-02-10 15:10:22 -08003957 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3958 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003959 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3960 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003961
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003962 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3963 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964
3965 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3966 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003967 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003968 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003969 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3970 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3972 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003973 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 }
3975
3976 virtualKey.keyCode = keyCode;
3977 virtualKey.flags = flags;
3978
3979 // convert the key definition's display coordinates into touch coordinates for a hit box
3980 int32_t halfWidth = virtualKeyDefinition.width / 2;
3981 int32_t halfHeight = virtualKeyDefinition.height / 2;
3982
3983 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3984 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3985 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3986 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3987 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3988 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3989 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3990 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003991 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003992 }
3993}
3994
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003995void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003996 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003997 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998
3999 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004000 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004001 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004002 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4003 i, virtualKey.scanCode, virtualKey.keyCode,
4004 virtualKey.hitLeft, virtualKey.hitRight,
4005 virtualKey.hitTop, virtualKey.hitBottom);
4006 }
4007 }
4008}
4009
4010void TouchInputMapper::parseCalibration() {
4011 const PropertyMap& in = getDevice()->getConfiguration();
4012 Calibration& out = mCalibration;
4013
4014 // Size
4015 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4016 String8 sizeCalibrationString;
4017 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4018 if (sizeCalibrationString == "none") {
4019 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4020 } else if (sizeCalibrationString == "geometric") {
4021 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4022 } else if (sizeCalibrationString == "diameter") {
4023 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4024 } else if (sizeCalibrationString == "box") {
4025 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4026 } else if (sizeCalibrationString == "area") {
4027 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4028 } else if (sizeCalibrationString != "default") {
4029 ALOGW("Invalid value for touch.size.calibration: '%s'",
4030 sizeCalibrationString.string());
4031 }
4032 }
4033
4034 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4035 out.sizeScale);
4036 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4037 out.sizeBias);
4038 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4039 out.sizeIsSummed);
4040
4041 // Pressure
4042 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4043 String8 pressureCalibrationString;
4044 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4045 if (pressureCalibrationString == "none") {
4046 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4047 } else if (pressureCalibrationString == "physical") {
4048 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4049 } else if (pressureCalibrationString == "amplitude") {
4050 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4051 } else if (pressureCalibrationString != "default") {
4052 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4053 pressureCalibrationString.string());
4054 }
4055 }
4056
4057 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4058 out.pressureScale);
4059
4060 // Orientation
4061 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4062 String8 orientationCalibrationString;
4063 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4064 if (orientationCalibrationString == "none") {
4065 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4066 } else if (orientationCalibrationString == "interpolated") {
4067 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4068 } else if (orientationCalibrationString == "vector") {
4069 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4070 } else if (orientationCalibrationString != "default") {
4071 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4072 orientationCalibrationString.string());
4073 }
4074 }
4075
4076 // Distance
4077 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4078 String8 distanceCalibrationString;
4079 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4080 if (distanceCalibrationString == "none") {
4081 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4082 } else if (distanceCalibrationString == "scaled") {
4083 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4084 } else if (distanceCalibrationString != "default") {
4085 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4086 distanceCalibrationString.string());
4087 }
4088 }
4089
4090 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4091 out.distanceScale);
4092
4093 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4094 String8 coverageCalibrationString;
4095 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4096 if (coverageCalibrationString == "none") {
4097 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4098 } else if (coverageCalibrationString == "box") {
4099 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4100 } else if (coverageCalibrationString != "default") {
4101 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4102 coverageCalibrationString.string());
4103 }
4104 }
4105}
4106
4107void TouchInputMapper::resolveCalibration() {
4108 // Size
4109 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4110 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4111 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4112 }
4113 } else {
4114 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4115 }
4116
4117 // Pressure
4118 if (mRawPointerAxes.pressure.valid) {
4119 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4120 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4121 }
4122 } else {
4123 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4124 }
4125
4126 // Orientation
4127 if (mRawPointerAxes.orientation.valid) {
4128 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4129 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4130 }
4131 } else {
4132 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4133 }
4134
4135 // Distance
4136 if (mRawPointerAxes.distance.valid) {
4137 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4138 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4139 }
4140 } else {
4141 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4142 }
4143
4144 // Coverage
4145 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4146 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4147 }
4148}
4149
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150void TouchInputMapper::dumpCalibration(std::string& dump) {
4151 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152
4153 // Size
4154 switch (mCalibration.sizeCalibration) {
4155 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 break;
4158 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 break;
4161 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 break;
4170 default:
4171 ALOG_ASSERT(false);
4172 }
4173
4174 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004175 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004176 mCalibration.sizeScale);
4177 }
4178
4179 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 mCalibration.sizeBias);
4182 }
4183
4184 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 toString(mCalibration.sizeIsSummed));
4187 }
4188
4189 // Pressure
4190 switch (mCalibration.pressureCalibration) {
4191 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 break;
4194 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004195 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004196 break;
4197 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 break;
4200 default:
4201 ALOG_ASSERT(false);
4202 }
4203
4204 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 mCalibration.pressureScale);
4207 }
4208
4209 // Orientation
4210 switch (mCalibration.orientationCalibration) {
4211 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 break;
4214 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004216 break;
4217 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 break;
4220 default:
4221 ALOG_ASSERT(false);
4222 }
4223
4224 // Distance
4225 switch (mCalibration.distanceCalibration) {
4226 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004227 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004228 break;
4229 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004230 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231 break;
4232 default:
4233 ALOG_ASSERT(false);
4234 }
4235
4236 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004237 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 mCalibration.distanceScale);
4239 }
4240
4241 switch (mCalibration.coverageCalibration) {
4242 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 break;
4245 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 break;
4248 default:
4249 ALOG_ASSERT(false);
4250 }
4251}
4252
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004253void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4254 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004255
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004256 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4257 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4258 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4259 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4260 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4261 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004262}
4263
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004264void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004265 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4266 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004267}
4268
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269void TouchInputMapper::reset(nsecs_t when) {
4270 mCursorButtonAccumulator.reset(getDevice());
4271 mCursorScrollAccumulator.reset(getDevice());
4272 mTouchButtonAccumulator.reset(getDevice());
4273
4274 mPointerVelocityControl.reset();
4275 mWheelXVelocityControl.reset();
4276 mWheelYVelocityControl.reset();
4277
Michael Wright842500e2015-03-13 17:32:02 -07004278 mRawStatesPending.clear();
4279 mCurrentRawState.clear();
4280 mCurrentCookedState.clear();
4281 mLastRawState.clear();
4282 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004283 mPointerUsage = POINTER_USAGE_NONE;
4284 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004285 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004286 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004287 mDownTime = 0;
4288
4289 mCurrentVirtualKey.down = false;
4290
4291 mPointerGesture.reset();
4292 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004293 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004294
Yi Kong9b14ac62018-07-17 13:48:38 -07004295 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004296 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4297 mPointerController->clearSpots();
4298 }
4299
4300 InputMapper::reset(when);
4301}
4302
Michael Wright842500e2015-03-13 17:32:02 -07004303void TouchInputMapper::resetExternalStylus() {
4304 mExternalStylusState.clear();
4305 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004306 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004307 mExternalStylusDataPending = false;
4308}
4309
Michael Wright43fd19f2015-04-21 19:02:58 +01004310void TouchInputMapper::clearStylusDataPendingFlags() {
4311 mExternalStylusDataPending = false;
4312 mExternalStylusFusionTimeout = LLONG_MAX;
4313}
4314
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004315void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4316 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4317 nsecs_t latency = now - evdevTime;
4318 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4319 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4320 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4321 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
Siarhei Vishniakou05247bb2019-03-22 17:11:21 -07004322 mStatistics.min, mStatistics.max,
4323 mStatistics.mean(), mStatistics.stdev(), mStatistics.count);
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004324 mStatistics.reset(now);
4325 }
4326}
4327
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328void TouchInputMapper::process(const RawEvent* rawEvent) {
4329 mCursorButtonAccumulator.process(rawEvent);
4330 mCursorScrollAccumulator.process(rawEvent);
4331 mTouchButtonAccumulator.process(rawEvent);
4332
4333 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004334 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004335 sync(rawEvent->when);
4336 }
4337}
4338
4339void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004340 const RawState* last = mRawStatesPending.empty() ?
4341 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004342
4343 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004344 mRawStatesPending.emplace_back();
4345
4346 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004347 next->clear();
4348 next->when = when;
4349
Michael Wrightd02c5b62014-02-10 15:10:22 -08004350 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004351 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004352 | mCursorButtonAccumulator.getButtonState();
4353
Michael Wright842500e2015-03-13 17:32:02 -07004354 // Sync scroll
4355 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4356 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357 mCursorScrollAccumulator.finishSync();
4358
Michael Wright842500e2015-03-13 17:32:02 -07004359 // Sync touch
4360 syncTouch(when, next);
4361
4362 // Assign pointer ids.
4363 if (!mHavePointerIds) {
4364 assignPointerIds(last, next);
4365 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004366
4367#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004368 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4369 "hovering ids 0x%08x -> 0x%08x",
4370 last->rawPointerData.pointerCount,
4371 next->rawPointerData.pointerCount,
4372 last->rawPointerData.touchingIdBits.value,
4373 next->rawPointerData.touchingIdBits.value,
4374 last->rawPointerData.hoveringIdBits.value,
4375 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376#endif
4377
Michael Wright842500e2015-03-13 17:32:02 -07004378 processRawTouches(false /*timeout*/);
4379}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004380
Michael Wright842500e2015-03-13 17:32:02 -07004381void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4383 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004384 mCurrentRawState.clear();
4385 mRawStatesPending.clear();
4386 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004387 }
4388
Michael Wright842500e2015-03-13 17:32:02 -07004389 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4390 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4391 // touching the current state will only observe the events that have been dispatched to the
4392 // rest of the pipeline.
4393 const size_t N = mRawStatesPending.size();
4394 size_t count;
4395 for(count = 0; count < N; count++) {
4396 const RawState& next = mRawStatesPending[count];
4397
4398 // A failure to assign the stylus id means that we're waiting on stylus data
4399 // and so should defer the rest of the pipeline.
4400 if (assignExternalStylusId(next, timeout)) {
4401 break;
4402 }
4403
4404 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004405 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004406 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004407 if (mCurrentRawState.when < mLastRawState.when) {
4408 mCurrentRawState.when = mLastRawState.when;
4409 }
Michael Wright842500e2015-03-13 17:32:02 -07004410 cookAndDispatch(mCurrentRawState.when);
4411 }
4412 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004413 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004414 }
4415
Michael Wright842500e2015-03-13 17:32:02 -07004416 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004417 if (timeout) {
4418 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4419 clearStylusDataPendingFlags();
4420 mCurrentRawState.copyFrom(mLastRawState);
4421#if DEBUG_STYLUS_FUSION
4422 ALOGD("Timeout expired, synthesizing event with new stylus data");
4423#endif
4424 cookAndDispatch(when);
4425 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4426 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4427 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4428 }
Michael Wright842500e2015-03-13 17:32:02 -07004429 }
4430}
4431
4432void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4433 // Always start with a clean state.
4434 mCurrentCookedState.clear();
4435
4436 // Apply stylus buttons to current raw state.
4437 applyExternalStylusButtonState(when);
4438
4439 // Handle policy on initial down or hover events.
4440 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4441 && mCurrentRawState.rawPointerData.pointerCount != 0;
4442
4443 uint32_t policyFlags = 0;
4444 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4445 if (initialDown || buttonsPressed) {
4446 // If this is a touch screen, hide the pointer on an initial down.
4447 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4448 getContext()->fadePointer();
4449 }
4450
4451 if (mParameters.wake) {
4452 policyFlags |= POLICY_FLAG_WAKE;
4453 }
4454 }
4455
4456 // Consume raw off-screen touches before cooking pointer data.
4457 // If touches are consumed, subsequent code will not receive any pointer data.
4458 if (consumeRawTouches(when, policyFlags)) {
4459 mCurrentRawState.rawPointerData.clear();
4460 }
4461
4462 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4463 // with cooked pointer data that has the same ids and indices as the raw data.
4464 // The following code can use either the raw or cooked data, as needed.
4465 cookPointerData();
4466
4467 // Apply stylus pressure to current cooked state.
4468 applyExternalStylusTouchState(when);
4469
4470 // Synthesize key down from raw buttons if needed.
4471 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004472 mViewport.displayId, policyFlags,
4473 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004474
4475 // Dispatch the touches either directly or by translation through a pointer on screen.
4476 if (mDeviceMode == DEVICE_MODE_POINTER) {
4477 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4478 !idBits.isEmpty(); ) {
4479 uint32_t id = idBits.clearFirstMarkedBit();
4480 const RawPointerData::Pointer& pointer =
4481 mCurrentRawState.rawPointerData.pointerForId(id);
4482 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4483 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4484 mCurrentCookedState.stylusIdBits.markBit(id);
4485 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4486 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4487 mCurrentCookedState.fingerIdBits.markBit(id);
4488 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4489 mCurrentCookedState.mouseIdBits.markBit(id);
4490 }
4491 }
4492 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4493 !idBits.isEmpty(); ) {
4494 uint32_t id = idBits.clearFirstMarkedBit();
4495 const RawPointerData::Pointer& pointer =
4496 mCurrentRawState.rawPointerData.pointerForId(id);
4497 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4498 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4499 mCurrentCookedState.stylusIdBits.markBit(id);
4500 }
4501 }
4502
4503 // Stylus takes precedence over all tools, then mouse, then finger.
4504 PointerUsage pointerUsage = mPointerUsage;
4505 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4506 mCurrentCookedState.mouseIdBits.clear();
4507 mCurrentCookedState.fingerIdBits.clear();
4508 pointerUsage = POINTER_USAGE_STYLUS;
4509 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4510 mCurrentCookedState.fingerIdBits.clear();
4511 pointerUsage = POINTER_USAGE_MOUSE;
4512 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4513 isPointerDown(mCurrentRawState.buttonState)) {
4514 pointerUsage = POINTER_USAGE_GESTURES;
4515 }
4516
4517 dispatchPointerUsage(when, policyFlags, pointerUsage);
4518 } else {
4519 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004520 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004521 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4522 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4523
4524 mPointerController->setButtonState(mCurrentRawState.buttonState);
4525 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4526 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004527 mCurrentCookedState.cookedPointerData.touchingIdBits,
4528 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004529 }
4530
Michael Wright8e812822015-06-22 16:18:21 +01004531 if (!mCurrentMotionAborted) {
4532 dispatchButtonRelease(when, policyFlags);
4533 dispatchHoverExit(when, policyFlags);
4534 dispatchTouches(when, policyFlags);
4535 dispatchHoverEnterAndMove(when, policyFlags);
4536 dispatchButtonPress(when, policyFlags);
4537 }
4538
4539 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4540 mCurrentMotionAborted = false;
4541 }
Michael Wright842500e2015-03-13 17:32:02 -07004542 }
4543
4544 // Synthesize key up from raw buttons if needed.
4545 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004546 mViewport.displayId, policyFlags,
4547 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004548
4549 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004550 mCurrentRawState.rawVScroll = 0;
4551 mCurrentRawState.rawHScroll = 0;
4552
4553 // Copy current touch to last touch in preparation for the next cycle.
4554 mLastRawState.copyFrom(mCurrentRawState);
4555 mLastCookedState.copyFrom(mCurrentCookedState);
4556}
4557
4558void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004559 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004560 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4561 }
4562}
4563
4564void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004565 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4566 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004567
Michael Wright53dca3a2015-04-23 17:39:53 +01004568 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4569 float pressure = mExternalStylusState.pressure;
4570 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4571 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4572 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4573 }
4574 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4575 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4576
4577 PointerProperties& properties =
4578 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004579 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4580 properties.toolType = mExternalStylusState.toolType;
4581 }
4582 }
4583}
4584
4585bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4586 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4587 return false;
4588 }
4589
4590 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4591 && state.rawPointerData.pointerCount != 0;
4592 if (initialDown) {
4593 if (mExternalStylusState.pressure != 0.0f) {
4594#if DEBUG_STYLUS_FUSION
4595 ALOGD("Have both stylus and touch data, beginning fusion");
4596#endif
4597 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4598 } else if (timeout) {
4599#if DEBUG_STYLUS_FUSION
4600 ALOGD("Timeout expired, assuming touch is not a stylus.");
4601#endif
4602 resetExternalStylus();
4603 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004604 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4605 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004606 }
4607#if DEBUG_STYLUS_FUSION
4608 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004609 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004610#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004611 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004612 return true;
4613 }
4614 }
4615
4616 // Check if the stylus pointer has gone up.
4617 if (mExternalStylusId != -1 &&
4618 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4619#if DEBUG_STYLUS_FUSION
4620 ALOGD("Stylus pointer is going up");
4621#endif
4622 mExternalStylusId = -1;
4623 }
4624
4625 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626}
4627
4628void TouchInputMapper::timeoutExpired(nsecs_t when) {
4629 if (mDeviceMode == DEVICE_MODE_POINTER) {
4630 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4631 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4632 }
Michael Wright842500e2015-03-13 17:32:02 -07004633 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004634 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004635 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004636 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4637 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004638 }
4639 }
4640}
4641
4642void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004643 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004644 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004645 // We're either in the middle of a fused stream of data or we're waiting on data before
4646 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4647 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004648 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004649 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 }
4651}
4652
4653bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4654 // Check for release of a virtual key.
4655 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004656 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004657 // Pointer went up while virtual key was down.
4658 mCurrentVirtualKey.down = false;
4659 if (!mCurrentVirtualKey.ignored) {
4660#if DEBUG_VIRTUAL_KEYS
4661 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4662 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4663#endif
4664 dispatchVirtualKey(when, policyFlags,
4665 AKEY_EVENT_ACTION_UP,
4666 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4667 }
4668 return true;
4669 }
4670
Michael Wright842500e2015-03-13 17:32:02 -07004671 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4672 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4673 const RawPointerData::Pointer& pointer =
4674 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4676 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4677 // Pointer is still within the space of the virtual key.
4678 return true;
4679 }
4680 }
4681
4682 // Pointer left virtual key area or another pointer also went down.
4683 // Send key cancellation but do not consume the touch yet.
4684 // This is useful when the user swipes through from the virtual key area
4685 // into the main display surface.
4686 mCurrentVirtualKey.down = false;
4687 if (!mCurrentVirtualKey.ignored) {
4688#if DEBUG_VIRTUAL_KEYS
4689 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4690 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4691#endif
4692 dispatchVirtualKey(when, policyFlags,
4693 AKEY_EVENT_ACTION_UP,
4694 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4695 | AKEY_EVENT_FLAG_CANCELED);
4696 }
4697 }
4698
Michael Wright842500e2015-03-13 17:32:02 -07004699 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4700 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004702 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4703 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004704 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4705 // If exactly one pointer went down, check for virtual key hit.
4706 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004707 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4709 if (virtualKey) {
4710 mCurrentVirtualKey.down = true;
4711 mCurrentVirtualKey.downTime = when;
4712 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4713 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4714 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4715 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4716
4717 if (!mCurrentVirtualKey.ignored) {
4718#if DEBUG_VIRTUAL_KEYS
4719 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4720 mCurrentVirtualKey.keyCode,
4721 mCurrentVirtualKey.scanCode);
4722#endif
4723 dispatchVirtualKey(when, policyFlags,
4724 AKEY_EVENT_ACTION_DOWN,
4725 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4726 }
4727 }
4728 }
4729 return true;
4730 }
4731 }
4732
4733 // Disable all virtual key touches that happen within a short time interval of the
4734 // most recent touch within the screen area. The idea is to filter out stray
4735 // virtual key presses when interacting with the touch screen.
4736 //
4737 // Problems we're trying to solve:
4738 //
4739 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4740 // virtual key area that is implemented by a separate touch panel and accidentally
4741 // triggers a virtual key.
4742 //
4743 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4744 // area and accidentally triggers a virtual key. This often happens when virtual keys
4745 // are layed out below the screen near to where the on screen keyboard's space bar
4746 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004747 if (mConfig.virtualKeyQuietTime > 0 &&
4748 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4750 }
4751 return false;
4752}
4753
4754void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4755 int32_t keyEventAction, int32_t keyEventFlags) {
4756 int32_t keyCode = mCurrentVirtualKey.keyCode;
4757 int32_t scanCode = mCurrentVirtualKey.scanCode;
4758 nsecs_t downTime = mCurrentVirtualKey.downTime;
4759 int32_t metaState = mContext->getGlobalMetaState();
4760 policyFlags |= POLICY_FLAG_VIRTUAL;
4761
Prabir Pradhan42611e02018-11-27 14:04:02 -08004762 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4763 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004764 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 getListener()->notifyKey(&args);
4766}
4767
Michael Wright8e812822015-06-22 16:18:21 +01004768void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4769 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4770 if (!currentIdBits.isEmpty()) {
4771 int32_t metaState = getContext()->getGlobalMetaState();
4772 int32_t buttonState = mCurrentCookedState.buttonState;
4773 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4774 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4775 mCurrentCookedState.cookedPointerData.pointerProperties,
4776 mCurrentCookedState.cookedPointerData.pointerCoords,
4777 mCurrentCookedState.cookedPointerData.idToIndex,
4778 currentIdBits, -1,
4779 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4780 mCurrentMotionAborted = true;
4781 }
4782}
4783
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004785 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4786 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004788 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789
4790 if (currentIdBits == lastIdBits) {
4791 if (!currentIdBits.isEmpty()) {
4792 // No pointer id changes so this is a move event.
4793 // The listener takes care of batching moves so we don't have to deal with that here.
4794 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004795 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004797 mCurrentCookedState.cookedPointerData.pointerProperties,
4798 mCurrentCookedState.cookedPointerData.pointerCoords,
4799 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 currentIdBits, -1,
4801 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4802 }
4803 } else {
4804 // There may be pointers going up and pointers going down and pointers moving
4805 // all at the same time.
4806 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4807 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4808 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4809 BitSet32 dispatchedIdBits(lastIdBits.value);
4810
4811 // Update last coordinates of pointers that have moved so that we observe the new
4812 // pointer positions at the same time as other pointers that have just gone up.
4813 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004814 mCurrentCookedState.cookedPointerData.pointerProperties,
4815 mCurrentCookedState.cookedPointerData.pointerCoords,
4816 mCurrentCookedState.cookedPointerData.idToIndex,
4817 mLastCookedState.cookedPointerData.pointerProperties,
4818 mLastCookedState.cookedPointerData.pointerCoords,
4819 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004820 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004821 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 moveNeeded = true;
4823 }
4824
4825 // Dispatch pointer up events.
4826 while (!upIdBits.isEmpty()) {
4827 uint32_t upId = upIdBits.clearFirstMarkedBit();
4828
4829 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004830 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004831 mLastCookedState.cookedPointerData.pointerProperties,
4832 mLastCookedState.cookedPointerData.pointerCoords,
4833 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004834 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004835 dispatchedIdBits.clearBit(upId);
4836 }
4837
4838 // Dispatch move events if any of the remaining pointers moved from their old locations.
4839 // Although applications receive new locations as part of individual pointer up
4840 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004841 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4843 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004844 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004845 mCurrentCookedState.cookedPointerData.pointerProperties,
4846 mCurrentCookedState.cookedPointerData.pointerCoords,
4847 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004848 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 }
4850
4851 // Dispatch pointer down events using the new pointer locations.
4852 while (!downIdBits.isEmpty()) {
4853 uint32_t downId = downIdBits.clearFirstMarkedBit();
4854 dispatchedIdBits.markBit(downId);
4855
4856 if (dispatchedIdBits.count() == 1) {
4857 // First pointer is going down. Set down time.
4858 mDownTime = when;
4859 }
4860
4861 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004862 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004863 mCurrentCookedState.cookedPointerData.pointerProperties,
4864 mCurrentCookedState.cookedPointerData.pointerCoords,
4865 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004866 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004867 }
4868 }
4869}
4870
4871void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4872 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004873 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4874 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875 int32_t metaState = getContext()->getGlobalMetaState();
4876 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004877 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004878 mLastCookedState.cookedPointerData.pointerProperties,
4879 mLastCookedState.cookedPointerData.pointerCoords,
4880 mLastCookedState.cookedPointerData.idToIndex,
4881 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4883 mSentHoverEnter = false;
4884 }
4885}
4886
4887void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004888 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4889 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004890 int32_t metaState = getContext()->getGlobalMetaState();
4891 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004892 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004893 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004894 mCurrentCookedState.cookedPointerData.pointerProperties,
4895 mCurrentCookedState.cookedPointerData.pointerCoords,
4896 mCurrentCookedState.cookedPointerData.idToIndex,
4897 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4899 mSentHoverEnter = true;
4900 }
4901
4902 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004903 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004904 mCurrentRawState.buttonState, 0,
4905 mCurrentCookedState.cookedPointerData.pointerProperties,
4906 mCurrentCookedState.cookedPointerData.pointerCoords,
4907 mCurrentCookedState.cookedPointerData.idToIndex,
4908 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004909 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4910 }
4911}
4912
Michael Wright7b159c92015-05-14 14:48:03 +01004913void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4914 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4915 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4916 const int32_t metaState = getContext()->getGlobalMetaState();
4917 int32_t buttonState = mLastCookedState.buttonState;
4918 while (!releasedButtons.isEmpty()) {
4919 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4920 buttonState &= ~actionButton;
4921 dispatchMotion(when, policyFlags, mSource,
4922 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4923 0, metaState, buttonState, 0,
4924 mCurrentCookedState.cookedPointerData.pointerProperties,
4925 mCurrentCookedState.cookedPointerData.pointerCoords,
4926 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4927 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4928 }
4929}
4930
4931void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4932 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4933 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4934 const int32_t metaState = getContext()->getGlobalMetaState();
4935 int32_t buttonState = mLastCookedState.buttonState;
4936 while (!pressedButtons.isEmpty()) {
4937 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4938 buttonState |= actionButton;
4939 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4940 0, metaState, buttonState, 0,
4941 mCurrentCookedState.cookedPointerData.pointerProperties,
4942 mCurrentCookedState.cookedPointerData.pointerCoords,
4943 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4944 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4945 }
4946}
4947
4948const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4949 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4950 return cookedPointerData.touchingIdBits;
4951 }
4952 return cookedPointerData.hoveringIdBits;
4953}
4954
Michael Wrightd02c5b62014-02-10 15:10:22 -08004955void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004956 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004957
Michael Wright842500e2015-03-13 17:32:02 -07004958 mCurrentCookedState.cookedPointerData.clear();
4959 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4960 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4961 mCurrentRawState.rawPointerData.hoveringIdBits;
4962 mCurrentCookedState.cookedPointerData.touchingIdBits =
4963 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964
Michael Wright7b159c92015-05-14 14:48:03 +01004965 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4966 mCurrentCookedState.buttonState = 0;
4967 } else {
4968 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4969 }
4970
Michael Wrightd02c5b62014-02-10 15:10:22 -08004971 // Walk through the the active pointers and map device coordinates onto
4972 // surface coordinates and adjust for display orientation.
4973 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004974 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004975
4976 // Size
4977 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4978 switch (mCalibration.sizeCalibration) {
4979 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4980 case Calibration::SIZE_CALIBRATION_DIAMETER:
4981 case Calibration::SIZE_CALIBRATION_BOX:
4982 case Calibration::SIZE_CALIBRATION_AREA:
4983 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4984 touchMajor = in.touchMajor;
4985 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4986 toolMajor = in.toolMajor;
4987 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4988 size = mRawPointerAxes.touchMinor.valid
4989 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4990 } else if (mRawPointerAxes.touchMajor.valid) {
4991 toolMajor = touchMajor = in.touchMajor;
4992 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4993 ? in.touchMinor : in.touchMajor;
4994 size = mRawPointerAxes.touchMinor.valid
4995 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4996 } else if (mRawPointerAxes.toolMajor.valid) {
4997 touchMajor = toolMajor = in.toolMajor;
4998 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4999 ? in.toolMinor : in.toolMajor;
5000 size = mRawPointerAxes.toolMinor.valid
5001 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5002 } else {
5003 ALOG_ASSERT(false, "No touch or tool axes. "
5004 "Size calibration should have been resolved to NONE.");
5005 touchMajor = 0;
5006 touchMinor = 0;
5007 toolMajor = 0;
5008 toolMinor = 0;
5009 size = 0;
5010 }
5011
5012 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005013 uint32_t touchingCount =
5014 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005015 if (touchingCount > 1) {
5016 touchMajor /= touchingCount;
5017 touchMinor /= touchingCount;
5018 toolMajor /= touchingCount;
5019 toolMinor /= touchingCount;
5020 size /= touchingCount;
5021 }
5022 }
5023
5024 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5025 touchMajor *= mGeometricScale;
5026 touchMinor *= mGeometricScale;
5027 toolMajor *= mGeometricScale;
5028 toolMinor *= mGeometricScale;
5029 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5030 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5031 touchMinor = touchMajor;
5032 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5033 toolMinor = toolMajor;
5034 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5035 touchMinor = touchMajor;
5036 toolMinor = toolMajor;
5037 }
5038
5039 mCalibration.applySizeScaleAndBias(&touchMajor);
5040 mCalibration.applySizeScaleAndBias(&touchMinor);
5041 mCalibration.applySizeScaleAndBias(&toolMajor);
5042 mCalibration.applySizeScaleAndBias(&toolMinor);
5043 size *= mSizeScale;
5044 break;
5045 default:
5046 touchMajor = 0;
5047 touchMinor = 0;
5048 toolMajor = 0;
5049 toolMinor = 0;
5050 size = 0;
5051 break;
5052 }
5053
5054 // Pressure
5055 float pressure;
5056 switch (mCalibration.pressureCalibration) {
5057 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5058 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5059 pressure = in.pressure * mPressureScale;
5060 break;
5061 default:
5062 pressure = in.isHovering ? 0 : 1;
5063 break;
5064 }
5065
5066 // Tilt and Orientation
5067 float tilt;
5068 float orientation;
5069 if (mHaveTilt) {
5070 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5071 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5072 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5073 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5074 } else {
5075 tilt = 0;
5076
5077 switch (mCalibration.orientationCalibration) {
5078 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5079 orientation = in.orientation * mOrientationScale;
5080 break;
5081 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5082 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5083 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5084 if (c1 != 0 || c2 != 0) {
5085 orientation = atan2f(c1, c2) * 0.5f;
5086 float confidence = hypotf(c1, c2);
5087 float scale = 1.0f + confidence / 16.0f;
5088 touchMajor *= scale;
5089 touchMinor /= scale;
5090 toolMajor *= scale;
5091 toolMinor /= scale;
5092 } else {
5093 orientation = 0;
5094 }
5095 break;
5096 }
5097 default:
5098 orientation = 0;
5099 }
5100 }
5101
5102 // Distance
5103 float distance;
5104 switch (mCalibration.distanceCalibration) {
5105 case Calibration::DISTANCE_CALIBRATION_SCALED:
5106 distance = in.distance * mDistanceScale;
5107 break;
5108 default:
5109 distance = 0;
5110 }
5111
5112 // Coverage
5113 int32_t rawLeft, rawTop, rawRight, rawBottom;
5114 switch (mCalibration.coverageCalibration) {
5115 case Calibration::COVERAGE_CALIBRATION_BOX:
5116 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5117 rawRight = in.toolMinor & 0x0000ffff;
5118 rawBottom = in.toolMajor & 0x0000ffff;
5119 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5120 break;
5121 default:
5122 rawLeft = rawTop = rawRight = rawBottom = 0;
5123 break;
5124 }
5125
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005126 // Adjust X,Y coords for device calibration
5127 // TODO: Adjust coverage coords?
5128 float xTransformed = in.x, yTransformed = in.y;
5129 mAffineTransform.applyTo(xTransformed, yTransformed);
5130
5131 // Adjust X, Y, and coverage coords for surface orientation.
5132 float x, y;
5133 float left, top, right, bottom;
5134
Michael Wrightd02c5b62014-02-10 15:10:22 -08005135 switch (mSurfaceOrientation) {
5136 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005137 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5138 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005139 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5140 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5141 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5142 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5143 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005144 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5146 }
5147 break;
5148 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005149 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005150 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005151 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5152 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5154 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5155 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005156 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005157 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5158 }
5159 break;
5160 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005161 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005162 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005163 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5164 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5166 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5167 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005168 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005169 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5170 }
5171 break;
5172 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005173 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5174 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5176 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5177 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5178 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5179 break;
5180 }
5181
5182 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005183 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005184 out.clear();
5185 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5186 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5187 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5188 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5189 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5190 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5191 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5192 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5194 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5195 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5196 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5197 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5198 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5199 } else {
5200 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5201 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5202 }
5203
5204 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005205 PointerProperties& properties =
5206 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207 uint32_t id = in.id;
5208 properties.clear();
5209 properties.id = id;
5210 properties.toolType = in.toolType;
5211
5212 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005213 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005214 }
5215}
5216
5217void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5218 PointerUsage pointerUsage) {
5219 if (pointerUsage != mPointerUsage) {
5220 abortPointerUsage(when, policyFlags);
5221 mPointerUsage = pointerUsage;
5222 }
5223
5224 switch (mPointerUsage) {
5225 case POINTER_USAGE_GESTURES:
5226 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5227 break;
5228 case POINTER_USAGE_STYLUS:
5229 dispatchPointerStylus(when, policyFlags);
5230 break;
5231 case POINTER_USAGE_MOUSE:
5232 dispatchPointerMouse(when, policyFlags);
5233 break;
5234 default:
5235 break;
5236 }
5237}
5238
5239void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5240 switch (mPointerUsage) {
5241 case POINTER_USAGE_GESTURES:
5242 abortPointerGestures(when, policyFlags);
5243 break;
5244 case POINTER_USAGE_STYLUS:
5245 abortPointerStylus(when, policyFlags);
5246 break;
5247 case POINTER_USAGE_MOUSE:
5248 abortPointerMouse(when, policyFlags);
5249 break;
5250 default:
5251 break;
5252 }
5253
5254 mPointerUsage = POINTER_USAGE_NONE;
5255}
5256
5257void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5258 bool isTimeout) {
5259 // Update current gesture coordinates.
5260 bool cancelPreviousGesture, finishPreviousGesture;
5261 bool sendEvents = preparePointerGestures(when,
5262 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5263 if (!sendEvents) {
5264 return;
5265 }
5266 if (finishPreviousGesture) {
5267 cancelPreviousGesture = false;
5268 }
5269
5270 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005271 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5272 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 if (finishPreviousGesture || cancelPreviousGesture) {
5274 mPointerController->clearSpots();
5275 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005276
5277 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5278 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5279 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005280 mPointerGesture.currentGestureIdBits,
5281 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005282 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283 } else {
5284 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5285 }
5286
5287 // Show or hide the pointer if needed.
5288 switch (mPointerGesture.currentGestureMode) {
5289 case PointerGesture::NEUTRAL:
5290 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005291 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5292 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005293 // Remind the user of where the pointer is after finishing a gesture with spots.
5294 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5295 }
5296 break;
5297 case PointerGesture::TAP:
5298 case PointerGesture::TAP_DRAG:
5299 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5300 case PointerGesture::HOVER:
5301 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005302 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005303 // Unfade the pointer when the current gesture manipulates the
5304 // area directly under the pointer.
5305 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5306 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005307 case PointerGesture::FREEFORM:
5308 // Fade the pointer when the current gesture manipulates a different
5309 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005310 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5312 } else {
5313 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5314 }
5315 break;
5316 }
5317
5318 // Send events!
5319 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005320 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321
5322 // Update last coordinates of pointers that have moved so that we observe the new
5323 // pointer positions at the same time as other pointers that have just gone up.
5324 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5325 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5326 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5327 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5328 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5329 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5330 bool moveNeeded = false;
5331 if (down && !cancelPreviousGesture && !finishPreviousGesture
5332 && !mPointerGesture.lastGestureIdBits.isEmpty()
5333 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5334 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5335 & mPointerGesture.lastGestureIdBits.value);
5336 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5337 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5338 mPointerGesture.lastGestureProperties,
5339 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5340 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005341 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 moveNeeded = true;
5343 }
5344 }
5345
5346 // Send motion events for all pointers that went up or were canceled.
5347 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5348 if (!dispatchedGestureIdBits.isEmpty()) {
5349 if (cancelPreviousGesture) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005350 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5351 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5352 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5353 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5354 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355
5356 dispatchedGestureIdBits.clear();
5357 } else {
5358 BitSet32 upGestureIdBits;
5359 if (finishPreviousGesture) {
5360 upGestureIdBits = dispatchedGestureIdBits;
5361 } else {
5362 upGestureIdBits.value = dispatchedGestureIdBits.value
5363 & ~mPointerGesture.currentGestureIdBits.value;
5364 }
5365 while (!upGestureIdBits.isEmpty()) {
5366 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5367
5368 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005369 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005370 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5371 mPointerGesture.lastGestureProperties,
5372 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5373 dispatchedGestureIdBits, id,
5374 0, 0, mPointerGesture.downTime);
5375
5376 dispatchedGestureIdBits.clearBit(id);
5377 }
5378 }
5379 }
5380
5381 // Send motion events for all pointers that moved.
5382 if (moveNeeded) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005383 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5384 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5385 mPointerGesture.currentGestureProperties,
5386 mPointerGesture.currentGestureCoords,
5387 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5388 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 }
5390
5391 // Send motion events for all pointers that went down.
5392 if (down) {
5393 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5394 & ~dispatchedGestureIdBits.value);
5395 while (!downGestureIdBits.isEmpty()) {
5396 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5397 dispatchedGestureIdBits.markBit(id);
5398
5399 if (dispatchedGestureIdBits.count() == 1) {
5400 mPointerGesture.downTime = when;
5401 }
5402
5403 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005404 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 mPointerGesture.currentGestureProperties,
5406 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5407 dispatchedGestureIdBits, id,
5408 0, 0, mPointerGesture.downTime);
5409 }
5410 }
5411
5412 // Send motion events for hover.
5413 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005414 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5415 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5416 mPointerGesture.currentGestureProperties,
5417 mPointerGesture.currentGestureCoords,
5418 mPointerGesture.currentGestureIdToIndex,
5419 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005420 } else if (dispatchedGestureIdBits.isEmpty()
5421 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5422 // Synthesize a hover move event after all pointers go up to indicate that
5423 // the pointer is hovering again even if the user is not currently touching
5424 // the touch pad. This ensures that a view will receive a fresh hover enter
5425 // event after a tap.
5426 float x, y;
5427 mPointerController->getPosition(&x, &y);
5428
5429 PointerProperties pointerProperties;
5430 pointerProperties.clear();
5431 pointerProperties.id = 0;
5432 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5433
5434 PointerCoords pointerCoords;
5435 pointerCoords.clear();
5436 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5437 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5438
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005439 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005440 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5441 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5442 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005443 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
5444 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005445 getListener()->notifyMotion(&args);
5446 }
5447
5448 // Update state.
5449 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5450 if (!down) {
5451 mPointerGesture.lastGestureIdBits.clear();
5452 } else {
5453 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5454 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5455 uint32_t id = idBits.clearFirstMarkedBit();
5456 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5457 mPointerGesture.lastGestureProperties[index].copyFrom(
5458 mPointerGesture.currentGestureProperties[index]);
5459 mPointerGesture.lastGestureCoords[index].copyFrom(
5460 mPointerGesture.currentGestureCoords[index]);
5461 mPointerGesture.lastGestureIdToIndex[id] = index;
5462 }
5463 }
5464}
5465
5466void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5467 // Cancel previously dispatches pointers.
5468 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5469 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005470 int32_t buttonState = mCurrentRawState.buttonState;
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005471 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5472 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5473 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5474 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5475 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005476 }
5477
5478 // Reset the current pointer gesture.
5479 mPointerGesture.reset();
5480 mPointerVelocityControl.reset();
5481
5482 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005483 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005484 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5485 mPointerController->clearSpots();
5486 }
5487}
5488
5489bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5490 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5491 *outCancelPreviousGesture = false;
5492 *outFinishPreviousGesture = false;
5493
5494 // Handle TAP timeout.
5495 if (isTimeout) {
5496#if DEBUG_GESTURES
5497 ALOGD("Gestures: Processing timeout");
5498#endif
5499
5500 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5501 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5502 // The tap/drag timeout has not yet expired.
5503 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5504 + mConfig.pointerGestureTapDragInterval);
5505 } else {
5506 // The tap is finished.
5507#if DEBUG_GESTURES
5508 ALOGD("Gestures: TAP finished");
5509#endif
5510 *outFinishPreviousGesture = true;
5511
5512 mPointerGesture.activeGestureId = -1;
5513 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5514 mPointerGesture.currentGestureIdBits.clear();
5515
5516 mPointerVelocityControl.reset();
5517 return true;
5518 }
5519 }
5520
5521 // We did not handle this timeout.
5522 return false;
5523 }
5524
Michael Wright842500e2015-03-13 17:32:02 -07005525 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5526 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527
5528 // Update the velocity tracker.
5529 {
5530 VelocityTracker::Position positions[MAX_POINTERS];
5531 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005532 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005534 const RawPointerData::Pointer& pointer =
5535 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 positions[count].x = pointer.x * mPointerXMovementScale;
5537 positions[count].y = pointer.y * mPointerYMovementScale;
5538 }
5539 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005540 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 }
5542
5543 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5544 // to NEUTRAL, then we should not generate tap event.
5545 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5546 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5547 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5548 mPointerGesture.resetTap();
5549 }
5550
5551 // Pick a new active touch id if needed.
5552 // Choose an arbitrary pointer that just went down, if there is one.
5553 // Otherwise choose an arbitrary remaining pointer.
5554 // This guarantees we always have an active touch id when there is at least one pointer.
5555 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5557 int32_t activeTouchId = lastActiveTouchId;
5558 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005559 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005561 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 mPointerGesture.firstTouchTime = when;
5563 }
Michael Wright842500e2015-03-13 17:32:02 -07005564 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005565 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005567 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 } else {
5569 activeTouchId = mPointerGesture.activeTouchId = -1;
5570 }
5571 }
5572
5573 // Determine whether we are in quiet time.
5574 bool isQuietTime = false;
5575 if (activeTouchId < 0) {
5576 mPointerGesture.resetQuietTime();
5577 } else {
5578 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5579 if (!isQuietTime) {
5580 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5581 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5582 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5583 && currentFingerCount < 2) {
5584 // Enter quiet time when exiting swipe or freeform state.
5585 // This is to prevent accidentally entering the hover state and flinging the
5586 // pointer when finishing a swipe and there is still one pointer left onscreen.
5587 isQuietTime = true;
5588 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5589 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005590 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005591 // Enter quiet time when releasing the button and there are still two or more
5592 // fingers down. This may indicate that one finger was used to press the button
5593 // but it has not gone up yet.
5594 isQuietTime = true;
5595 }
5596 if (isQuietTime) {
5597 mPointerGesture.quietTime = when;
5598 }
5599 }
5600 }
5601
5602 // Switch states based on button and pointer state.
5603 if (isQuietTime) {
5604 // Case 1: Quiet time. (QUIET)
5605#if DEBUG_GESTURES
5606 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5607 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5608#endif
5609 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5610 *outFinishPreviousGesture = true;
5611 }
5612
5613 mPointerGesture.activeGestureId = -1;
5614 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5615 mPointerGesture.currentGestureIdBits.clear();
5616
5617 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005618 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005619 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5620 // The pointer follows the active touch point.
5621 // Emit DOWN, MOVE, UP events at the pointer location.
5622 //
5623 // Only the active touch matters; other fingers are ignored. This policy helps
5624 // to handle the case where the user places a second finger on the touch pad
5625 // to apply the necessary force to depress an integrated button below the surface.
5626 // We don't want the second finger to be delivered to applications.
5627 //
5628 // For this to work well, we need to make sure to track the pointer that is really
5629 // active. If the user first puts one finger down to click then adds another
5630 // finger to drag then the active pointer should switch to the finger that is
5631 // being dragged.
5632#if DEBUG_GESTURES
5633 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5634 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5635#endif
5636 // Reset state when just starting.
5637 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5638 *outFinishPreviousGesture = true;
5639 mPointerGesture.activeGestureId = 0;
5640 }
5641
5642 // Switch pointers if needed.
5643 // Find the fastest pointer and follow it.
5644 if (activeTouchId >= 0 && currentFingerCount > 1) {
5645 int32_t bestId = -1;
5646 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005647 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 uint32_t id = idBits.clearFirstMarkedBit();
5649 float vx, vy;
5650 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5651 float speed = hypotf(vx, vy);
5652 if (speed > bestSpeed) {
5653 bestId = id;
5654 bestSpeed = speed;
5655 }
5656 }
5657 }
5658 if (bestId >= 0 && bestId != activeTouchId) {
5659 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005660#if DEBUG_GESTURES
5661 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5662 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5663#endif
5664 }
5665 }
5666
Jun Mukaifa1706a2015-12-03 01:14:46 -08005667 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005668 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005670 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005671 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005672 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005673 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5674 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675
5676 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5677 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5678
5679 // Move the pointer using a relative motion.
5680 // When using spots, the click will occur at the position of the anchor
5681 // spot and all other spots will move there.
5682 mPointerController->move(deltaX, deltaY);
5683 } else {
5684 mPointerVelocityControl.reset();
5685 }
5686
5687 float x, y;
5688 mPointerController->getPosition(&x, &y);
5689
5690 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5691 mPointerGesture.currentGestureIdBits.clear();
5692 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5693 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5694 mPointerGesture.currentGestureProperties[0].clear();
5695 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5696 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5697 mPointerGesture.currentGestureCoords[0].clear();
5698 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5699 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5700 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5701 } else if (currentFingerCount == 0) {
5702 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5703 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5704 *outFinishPreviousGesture = true;
5705 }
5706
5707 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5708 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5709 bool tapped = false;
5710 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5711 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5712 && lastFingerCount == 1) {
5713 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5714 float x, y;
5715 mPointerController->getPosition(&x, &y);
5716 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5717 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5718#if DEBUG_GESTURES
5719 ALOGD("Gestures: TAP");
5720#endif
5721
5722 mPointerGesture.tapUpTime = when;
5723 getContext()->requestTimeoutAtTime(when
5724 + mConfig.pointerGestureTapDragInterval);
5725
5726 mPointerGesture.activeGestureId = 0;
5727 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5728 mPointerGesture.currentGestureIdBits.clear();
5729 mPointerGesture.currentGestureIdBits.markBit(
5730 mPointerGesture.activeGestureId);
5731 mPointerGesture.currentGestureIdToIndex[
5732 mPointerGesture.activeGestureId] = 0;
5733 mPointerGesture.currentGestureProperties[0].clear();
5734 mPointerGesture.currentGestureProperties[0].id =
5735 mPointerGesture.activeGestureId;
5736 mPointerGesture.currentGestureProperties[0].toolType =
5737 AMOTION_EVENT_TOOL_TYPE_FINGER;
5738 mPointerGesture.currentGestureCoords[0].clear();
5739 mPointerGesture.currentGestureCoords[0].setAxisValue(
5740 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5741 mPointerGesture.currentGestureCoords[0].setAxisValue(
5742 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5743 mPointerGesture.currentGestureCoords[0].setAxisValue(
5744 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5745
5746 tapped = true;
5747 } else {
5748#if DEBUG_GESTURES
5749 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5750 x - mPointerGesture.tapX,
5751 y - mPointerGesture.tapY);
5752#endif
5753 }
5754 } else {
5755#if DEBUG_GESTURES
5756 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5757 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5758 (when - mPointerGesture.tapDownTime) * 0.000001f);
5759 } else {
5760 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5761 }
5762#endif
5763 }
5764 }
5765
5766 mPointerVelocityControl.reset();
5767
5768 if (!tapped) {
5769#if DEBUG_GESTURES
5770 ALOGD("Gestures: NEUTRAL");
5771#endif
5772 mPointerGesture.activeGestureId = -1;
5773 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5774 mPointerGesture.currentGestureIdBits.clear();
5775 }
5776 } else if (currentFingerCount == 1) {
5777 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5778 // The pointer follows the active touch point.
5779 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5780 // When in TAP_DRAG, emit MOVE events at the pointer location.
5781 ALOG_ASSERT(activeTouchId >= 0);
5782
5783 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5784 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5785 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5786 float x, y;
5787 mPointerController->getPosition(&x, &y);
5788 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5789 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5790 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5791 } else {
5792#if DEBUG_GESTURES
5793 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5794 x - mPointerGesture.tapX,
5795 y - mPointerGesture.tapY);
5796#endif
5797 }
5798 } else {
5799#if DEBUG_GESTURES
5800 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5801 (when - mPointerGesture.tapUpTime) * 0.000001f);
5802#endif
5803 }
5804 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5805 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5806 }
5807
Jun Mukaifa1706a2015-12-03 01:14:46 -08005808 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005809 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005811 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005812 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005813 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005814 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5815 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816
5817 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5818 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5819
5820 // Move the pointer using a relative motion.
5821 // When using spots, the hover or drag will occur at the position of the anchor spot.
5822 mPointerController->move(deltaX, deltaY);
5823 } else {
5824 mPointerVelocityControl.reset();
5825 }
5826
5827 bool down;
5828 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5829#if DEBUG_GESTURES
5830 ALOGD("Gestures: TAP_DRAG");
5831#endif
5832 down = true;
5833 } else {
5834#if DEBUG_GESTURES
5835 ALOGD("Gestures: HOVER");
5836#endif
5837 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5838 *outFinishPreviousGesture = true;
5839 }
5840 mPointerGesture.activeGestureId = 0;
5841 down = false;
5842 }
5843
5844 float x, y;
5845 mPointerController->getPosition(&x, &y);
5846
5847 mPointerGesture.currentGestureIdBits.clear();
5848 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5849 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5850 mPointerGesture.currentGestureProperties[0].clear();
5851 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5852 mPointerGesture.currentGestureProperties[0].toolType =
5853 AMOTION_EVENT_TOOL_TYPE_FINGER;
5854 mPointerGesture.currentGestureCoords[0].clear();
5855 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5856 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5857 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5858 down ? 1.0f : 0.0f);
5859
5860 if (lastFingerCount == 0 && currentFingerCount != 0) {
5861 mPointerGesture.resetTap();
5862 mPointerGesture.tapDownTime = when;
5863 mPointerGesture.tapX = x;
5864 mPointerGesture.tapY = y;
5865 }
5866 } else {
5867 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5868 // We need to provide feedback for each finger that goes down so we cannot wait
5869 // for the fingers to move before deciding what to do.
5870 //
5871 // The ambiguous case is deciding what to do when there are two fingers down but they
5872 // have not moved enough to determine whether they are part of a drag or part of a
5873 // freeform gesture, or just a press or long-press at the pointer location.
5874 //
5875 // When there are two fingers we start with the PRESS hypothesis and we generate a
5876 // down at the pointer location.
5877 //
5878 // When the two fingers move enough or when additional fingers are added, we make
5879 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5880 ALOG_ASSERT(activeTouchId >= 0);
5881
5882 bool settled = when >= mPointerGesture.firstTouchTime
5883 + mConfig.pointerGestureMultitouchSettleInterval;
5884 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5885 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5886 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5887 *outFinishPreviousGesture = true;
5888 } else if (!settled && currentFingerCount > lastFingerCount) {
5889 // Additional pointers have gone down but not yet settled.
5890 // Reset the gesture.
5891#if DEBUG_GESTURES
5892 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5893 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5894 + mConfig.pointerGestureMultitouchSettleInterval - when)
5895 * 0.000001f);
5896#endif
5897 *outCancelPreviousGesture = true;
5898 } else {
5899 // Continue previous gesture.
5900 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5901 }
5902
5903 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5904 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5905 mPointerGesture.activeGestureId = 0;
5906 mPointerGesture.referenceIdBits.clear();
5907 mPointerVelocityControl.reset();
5908
5909 // Use the centroid and pointer location as the reference points for the gesture.
5910#if DEBUG_GESTURES
5911 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5912 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5913 + mConfig.pointerGestureMultitouchSettleInterval - when)
5914 * 0.000001f);
5915#endif
Michael Wright842500e2015-03-13 17:32:02 -07005916 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005917 &mPointerGesture.referenceTouchX,
5918 &mPointerGesture.referenceTouchY);
5919 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5920 &mPointerGesture.referenceGestureY);
5921 }
5922
5923 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005924 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005925 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5926 uint32_t id = idBits.clearFirstMarkedBit();
5927 mPointerGesture.referenceDeltas[id].dx = 0;
5928 mPointerGesture.referenceDeltas[id].dy = 0;
5929 }
Michael Wright842500e2015-03-13 17:32:02 -07005930 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931
5932 // Add delta for all fingers and calculate a common movement delta.
5933 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005934 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5935 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5937 bool first = (idBits == commonIdBits);
5938 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005939 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5940 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005941 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5942 delta.dx += cpd.x - lpd.x;
5943 delta.dy += cpd.y - lpd.y;
5944
5945 if (first) {
5946 commonDeltaX = delta.dx;
5947 commonDeltaY = delta.dy;
5948 } else {
5949 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5950 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5951 }
5952 }
5953
5954 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5955 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5956 float dist[MAX_POINTER_ID + 1];
5957 int32_t distOverThreshold = 0;
5958 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5959 uint32_t id = idBits.clearFirstMarkedBit();
5960 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5961 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5962 delta.dy * mPointerYZoomScale);
5963 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5964 distOverThreshold += 1;
5965 }
5966 }
5967
5968 // Only transition when at least two pointers have moved further than
5969 // the minimum distance threshold.
5970 if (distOverThreshold >= 2) {
5971 if (currentFingerCount > 2) {
5972 // There are more than two pointers, switch to FREEFORM.
5973#if DEBUG_GESTURES
5974 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5975 currentFingerCount);
5976#endif
5977 *outCancelPreviousGesture = true;
5978 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5979 } else {
5980 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005981 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005982 uint32_t id1 = idBits.clearFirstMarkedBit();
5983 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005984 const RawPointerData::Pointer& p1 =
5985 mCurrentRawState.rawPointerData.pointerForId(id1);
5986 const RawPointerData::Pointer& p2 =
5987 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5989 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5990 // There are two pointers but they are too far apart for a SWIPE,
5991 // switch to FREEFORM.
5992#if DEBUG_GESTURES
5993 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5994 mutualDistance, mPointerGestureMaxSwipeWidth);
5995#endif
5996 *outCancelPreviousGesture = true;
5997 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5998 } else {
5999 // There are two pointers. Wait for both pointers to start moving
6000 // before deciding whether this is a SWIPE or FREEFORM gesture.
6001 float dist1 = dist[id1];
6002 float dist2 = dist[id2];
6003 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6004 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6005 // Calculate the dot product of the displacement vectors.
6006 // When the vectors are oriented in approximately the same direction,
6007 // the angle betweeen them is near zero and the cosine of the angle
6008 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6009 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6010 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6011 float dx1 = delta1.dx * mPointerXZoomScale;
6012 float dy1 = delta1.dy * mPointerYZoomScale;
6013 float dx2 = delta2.dx * mPointerXZoomScale;
6014 float dy2 = delta2.dy * mPointerYZoomScale;
6015 float dot = dx1 * dx2 + dy1 * dy2;
6016 float cosine = dot / (dist1 * dist2); // denominator always > 0
6017 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6018 // Pointers are moving in the same direction. Switch to SWIPE.
6019#if DEBUG_GESTURES
6020 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6021 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6022 "cosine %0.3f >= %0.3f",
6023 dist1, mConfig.pointerGestureMultitouchMinDistance,
6024 dist2, mConfig.pointerGestureMultitouchMinDistance,
6025 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6026#endif
6027 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6028 } else {
6029 // Pointers are moving in different directions. Switch to FREEFORM.
6030#if DEBUG_GESTURES
6031 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6032 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6033 "cosine %0.3f < %0.3f",
6034 dist1, mConfig.pointerGestureMultitouchMinDistance,
6035 dist2, mConfig.pointerGestureMultitouchMinDistance,
6036 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6037#endif
6038 *outCancelPreviousGesture = true;
6039 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6040 }
6041 }
6042 }
6043 }
6044 }
6045 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6046 // Switch from SWIPE to FREEFORM if additional pointers go down.
6047 // Cancel previous gesture.
6048 if (currentFingerCount > 2) {
6049#if DEBUG_GESTURES
6050 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6051 currentFingerCount);
6052#endif
6053 *outCancelPreviousGesture = true;
6054 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6055 }
6056 }
6057
6058 // Move the reference points based on the overall group motion of the fingers
6059 // except in PRESS mode while waiting for a transition to occur.
6060 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6061 && (commonDeltaX || commonDeltaY)) {
6062 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6063 uint32_t id = idBits.clearFirstMarkedBit();
6064 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6065 delta.dx = 0;
6066 delta.dy = 0;
6067 }
6068
6069 mPointerGesture.referenceTouchX += commonDeltaX;
6070 mPointerGesture.referenceTouchY += commonDeltaY;
6071
6072 commonDeltaX *= mPointerXMovementScale;
6073 commonDeltaY *= mPointerYMovementScale;
6074
6075 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6076 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6077
6078 mPointerGesture.referenceGestureX += commonDeltaX;
6079 mPointerGesture.referenceGestureY += commonDeltaY;
6080 }
6081
6082 // Report gestures.
6083 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6084 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6085 // PRESS or SWIPE mode.
6086#if DEBUG_GESTURES
6087 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6088 "activeGestureId=%d, currentTouchPointerCount=%d",
6089 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6090#endif
6091 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6092
6093 mPointerGesture.currentGestureIdBits.clear();
6094 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6095 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6096 mPointerGesture.currentGestureProperties[0].clear();
6097 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6098 mPointerGesture.currentGestureProperties[0].toolType =
6099 AMOTION_EVENT_TOOL_TYPE_FINGER;
6100 mPointerGesture.currentGestureCoords[0].clear();
6101 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6102 mPointerGesture.referenceGestureX);
6103 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6104 mPointerGesture.referenceGestureY);
6105 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6106 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6107 // FREEFORM mode.
6108#if DEBUG_GESTURES
6109 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6110 "activeGestureId=%d, currentTouchPointerCount=%d",
6111 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6112#endif
6113 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6114
6115 mPointerGesture.currentGestureIdBits.clear();
6116
6117 BitSet32 mappedTouchIdBits;
6118 BitSet32 usedGestureIdBits;
6119 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6120 // Initially, assign the active gesture id to the active touch point
6121 // if there is one. No other touch id bits are mapped yet.
6122 if (!*outCancelPreviousGesture) {
6123 mappedTouchIdBits.markBit(activeTouchId);
6124 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6125 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6126 mPointerGesture.activeGestureId;
6127 } else {
6128 mPointerGesture.activeGestureId = -1;
6129 }
6130 } else {
6131 // Otherwise, assume we mapped all touches from the previous frame.
6132 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006133 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6134 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006135 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6136
6137 // Check whether we need to choose a new active gesture id because the
6138 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006139 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6140 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 !upTouchIdBits.isEmpty(); ) {
6142 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6143 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6144 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6145 mPointerGesture.activeGestureId = -1;
6146 break;
6147 }
6148 }
6149 }
6150
6151#if DEBUG_GESTURES
6152 ALOGD("Gestures: FREEFORM follow up "
6153 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6154 "activeGestureId=%d",
6155 mappedTouchIdBits.value, usedGestureIdBits.value,
6156 mPointerGesture.activeGestureId);
6157#endif
6158
Michael Wright842500e2015-03-13 17:32:02 -07006159 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006160 for (uint32_t i = 0; i < currentFingerCount; i++) {
6161 uint32_t touchId = idBits.clearFirstMarkedBit();
6162 uint32_t gestureId;
6163 if (!mappedTouchIdBits.hasBit(touchId)) {
6164 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6165 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6166#if DEBUG_GESTURES
6167 ALOGD("Gestures: FREEFORM "
6168 "new mapping for touch id %d -> gesture id %d",
6169 touchId, gestureId);
6170#endif
6171 } else {
6172 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6173#if DEBUG_GESTURES
6174 ALOGD("Gestures: FREEFORM "
6175 "existing mapping for touch id %d -> gesture id %d",
6176 touchId, gestureId);
6177#endif
6178 }
6179 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6180 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6181
6182 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006183 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006184 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6185 * mPointerXZoomScale;
6186 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6187 * mPointerYZoomScale;
6188 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6189
6190 mPointerGesture.currentGestureProperties[i].clear();
6191 mPointerGesture.currentGestureProperties[i].id = gestureId;
6192 mPointerGesture.currentGestureProperties[i].toolType =
6193 AMOTION_EVENT_TOOL_TYPE_FINGER;
6194 mPointerGesture.currentGestureCoords[i].clear();
6195 mPointerGesture.currentGestureCoords[i].setAxisValue(
6196 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6197 mPointerGesture.currentGestureCoords[i].setAxisValue(
6198 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6199 mPointerGesture.currentGestureCoords[i].setAxisValue(
6200 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6201 }
6202
6203 if (mPointerGesture.activeGestureId < 0) {
6204 mPointerGesture.activeGestureId =
6205 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6206#if DEBUG_GESTURES
6207 ALOGD("Gestures: FREEFORM new "
6208 "activeGestureId=%d", mPointerGesture.activeGestureId);
6209#endif
6210 }
6211 }
6212 }
6213
Michael Wright842500e2015-03-13 17:32:02 -07006214 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006215
6216#if DEBUG_GESTURES
6217 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6218 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6219 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6220 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6221 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6222 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6223 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6224 uint32_t id = idBits.clearFirstMarkedBit();
6225 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6226 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6227 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6228 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6229 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6230 id, index, properties.toolType,
6231 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6232 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6233 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6234 }
6235 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6236 uint32_t id = idBits.clearFirstMarkedBit();
6237 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6238 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6239 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6240 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6241 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6242 id, index, properties.toolType,
6243 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6244 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6245 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6246 }
6247#endif
6248 return true;
6249}
6250
6251void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6252 mPointerSimple.currentCoords.clear();
6253 mPointerSimple.currentProperties.clear();
6254
6255 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006256 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6257 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6258 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6259 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6260 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006261 mPointerController->setPosition(x, y);
6262
Michael Wright842500e2015-03-13 17:32:02 -07006263 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 down = !hovering;
6265
6266 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006267 mPointerSimple.currentCoords.copyFrom(
6268 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6270 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6271 mPointerSimple.currentProperties.id = 0;
6272 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006273 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006274 } else {
6275 down = false;
6276 hovering = false;
6277 }
6278
6279 dispatchPointerSimple(when, policyFlags, down, hovering);
6280}
6281
6282void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6283 abortPointerSimple(when, policyFlags);
6284}
6285
6286void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6287 mPointerSimple.currentCoords.clear();
6288 mPointerSimple.currentProperties.clear();
6289
6290 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006291 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6292 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6293 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006294 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006295 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6296 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006297 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006298 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006300 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006301 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006302 * mPointerYMovementScale;
6303
6304 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6305 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6306
6307 mPointerController->move(deltaX, deltaY);
6308 } else {
6309 mPointerVelocityControl.reset();
6310 }
6311
Michael Wright842500e2015-03-13 17:32:02 -07006312 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 hovering = !down;
6314
6315 float x, y;
6316 mPointerController->getPosition(&x, &y);
6317 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006318 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6320 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6321 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6322 hovering ? 0.0f : 1.0f);
6323 mPointerSimple.currentProperties.id = 0;
6324 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006325 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006326 } else {
6327 mPointerVelocityControl.reset();
6328
6329 down = false;
6330 hovering = false;
6331 }
6332
6333 dispatchPointerSimple(when, policyFlags, down, hovering);
6334}
6335
6336void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6337 abortPointerSimple(when, policyFlags);
6338
6339 mPointerVelocityControl.reset();
6340}
6341
6342void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6343 bool down, bool hovering) {
6344 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006345 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346
Garfield Tan00f511d2019-06-12 16:55:40 -07006347 if (down || hovering) {
6348 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6349 mPointerController->clearSpots();
6350 mPointerController->setButtonState(mCurrentRawState.buttonState);
6351 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6352 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6353 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006355 displayId = mPointerController->getDisplayId();
6356
6357 float xCursorPosition;
6358 float yCursorPosition;
6359 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360
6361 if (mPointerSimple.down && !down) {
6362 mPointerSimple.down = false;
6363
6364 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006365 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6366 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6367 mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006368 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6369 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6370 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6371 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 getListener()->notifyMotion(&args);
6373 }
6374
6375 if (mPointerSimple.hovering && !hovering) {
6376 mPointerSimple.hovering = false;
6377
6378 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006379 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6380 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6381 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006382 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6383 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6384 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6385 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006386 getListener()->notifyMotion(&args);
6387 }
6388
6389 if (down) {
6390 if (!mPointerSimple.down) {
6391 mPointerSimple.down = true;
6392 mPointerSimple.downTime = when;
6393
6394 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006395 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6396 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6397 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006398 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6399 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6400 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6401 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 getListener()->notifyMotion(&args);
6403 }
6404
6405 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006406 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6407 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6408 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006409 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6410 &mPointerSimple.currentCoords, mOrientedXPrecision,
6411 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6412 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006413 getListener()->notifyMotion(&args);
6414 }
6415
6416 if (hovering) {
6417 if (!mPointerSimple.hovering) {
6418 mPointerSimple.hovering = true;
6419
6420 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006421 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6422 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6423 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006424 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6425 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6426 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6427 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006428 getListener()->notifyMotion(&args);
6429 }
6430
6431 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006432 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6433 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6434 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006435 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6436 &mPointerSimple.currentCoords, mOrientedXPrecision,
6437 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6438 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006439 getListener()->notifyMotion(&args);
6440 }
6441
Michael Wright842500e2015-03-13 17:32:02 -07006442 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6443 float vscroll = mCurrentRawState.rawVScroll;
6444 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006445 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6446 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006447
6448 // Send scroll.
6449 PointerCoords pointerCoords;
6450 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6451 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6452 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6453
Garfield Tan00f511d2019-06-12 16:55:40 -07006454 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6455 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6456 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006457 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6458 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
6459 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6460 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461 getListener()->notifyMotion(&args);
6462 }
6463
6464 // Save state.
6465 if (down || hovering) {
6466 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6467 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6468 } else {
6469 mPointerSimple.reset();
6470 }
6471}
6472
6473void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6474 mPointerSimple.currentCoords.clear();
6475 mPointerSimple.currentProperties.clear();
6476
6477 dispatchPointerSimple(when, policyFlags, false, false);
6478}
6479
6480void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006481 int32_t action, int32_t actionButton, int32_t flags,
6482 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6483 const PointerProperties* properties,
6484 const PointerCoords* coords, const uint32_t* idToIndex,
6485 BitSet32 idBits, int32_t changedId, float xPrecision,
6486 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006487 PointerCoords pointerCoords[MAX_POINTERS];
6488 PointerProperties pointerProperties[MAX_POINTERS];
6489 uint32_t pointerCount = 0;
6490 while (!idBits.isEmpty()) {
6491 uint32_t id = idBits.clearFirstMarkedBit();
6492 uint32_t index = idToIndex[id];
6493 pointerProperties[pointerCount].copyFrom(properties[index]);
6494 pointerCoords[pointerCount].copyFrom(coords[index]);
6495
6496 if (changedId >= 0 && id == uint32_t(changedId)) {
6497 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6498 }
6499
6500 pointerCount += 1;
6501 }
6502
6503 ALOG_ASSERT(pointerCount != 0);
6504
6505 if (changedId >= 0 && pointerCount == 1) {
6506 // Replace initial down and final up action.
6507 // We can compare the action without masking off the changed pointer index
6508 // because we know the index is 0.
6509 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6510 action = AMOTION_EVENT_ACTION_DOWN;
6511 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6512 action = AMOTION_EVENT_ACTION_UP;
6513 } else {
6514 // Can't happen.
6515 ALOG_ASSERT(false);
6516 }
6517 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006518 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6519 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6520 if (mDeviceMode == DEVICE_MODE_POINTER) {
6521 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6522 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006523 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006524 const int32_t deviceId = getDeviceId();
6525 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006526 std::for_each(frames.begin(), frames.end(),
6527 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006528 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6529 policyFlags, action, actionButton, flags, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006530 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
6531 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
6532 downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006533 getListener()->notifyMotion(&args);
6534}
6535
6536bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6537 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6538 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6539 BitSet32 idBits) const {
6540 bool changed = false;
6541 while (!idBits.isEmpty()) {
6542 uint32_t id = idBits.clearFirstMarkedBit();
6543 uint32_t inIndex = inIdToIndex[id];
6544 uint32_t outIndex = outIdToIndex[id];
6545
6546 const PointerProperties& curInProperties = inProperties[inIndex];
6547 const PointerCoords& curInCoords = inCoords[inIndex];
6548 PointerProperties& curOutProperties = outProperties[outIndex];
6549 PointerCoords& curOutCoords = outCoords[outIndex];
6550
6551 if (curInProperties != curOutProperties) {
6552 curOutProperties.copyFrom(curInProperties);
6553 changed = true;
6554 }
6555
6556 if (curInCoords != curOutCoords) {
6557 curOutCoords.copyFrom(curInCoords);
6558 changed = true;
6559 }
6560 }
6561 return changed;
6562}
6563
6564void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006565 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6567 }
6568}
6569
Jeff Brownc9aa6282015-02-11 19:03:28 -08006570void TouchInputMapper::cancelTouch(nsecs_t when) {
6571 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006572 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006573}
6574
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006576 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006577 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006578 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006579 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6580 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6581 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006582}
6583
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006584const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006586 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006587#if DEBUG_VIRTUAL_KEYS
6588 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6589 "left=%d, top=%d, right=%d, bottom=%d",
6590 x, y,
6591 virtualKey.keyCode, virtualKey.scanCode,
6592 virtualKey.hitLeft, virtualKey.hitTop,
6593 virtualKey.hitRight, virtualKey.hitBottom);
6594#endif
6595
6596 if (virtualKey.isHit(x, y)) {
6597 return & virtualKey;
6598 }
6599 }
6600
Yi Kong9b14ac62018-07-17 13:48:38 -07006601 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006602}
6603
Michael Wright842500e2015-03-13 17:32:02 -07006604void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6605 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6606 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607
Michael Wright842500e2015-03-13 17:32:02 -07006608 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609
6610 if (currentPointerCount == 0) {
6611 // No pointers to assign.
6612 return;
6613 }
6614
6615 if (lastPointerCount == 0) {
6616 // All pointers are new.
6617 for (uint32_t i = 0; i < currentPointerCount; i++) {
6618 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006619 current->rawPointerData.pointers[i].id = id;
6620 current->rawPointerData.idToIndex[id] = i;
6621 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006622 }
6623 return;
6624 }
6625
6626 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006627 && current->rawPointerData.pointers[0].toolType
6628 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006629 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006630 uint32_t id = last->rawPointerData.pointers[0].id;
6631 current->rawPointerData.pointers[0].id = id;
6632 current->rawPointerData.idToIndex[id] = 0;
6633 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006634 return;
6635 }
6636
6637 // General case.
6638 // We build a heap of squared euclidean distances between current and last pointers
6639 // associated with the current and last pointer indices. Then, we find the best
6640 // match (by distance) for each current pointer.
6641 // The pointers must have the same tool type but it is possible for them to
6642 // transition from hovering to touching or vice-versa while retaining the same id.
6643 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6644
6645 uint32_t heapSize = 0;
6646 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6647 currentPointerIndex++) {
6648 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6649 lastPointerIndex++) {
6650 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006651 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006652 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006653 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006654 if (currentPointer.toolType == lastPointer.toolType) {
6655 int64_t deltaX = currentPointer.x - lastPointer.x;
6656 int64_t deltaY = currentPointer.y - lastPointer.y;
6657
6658 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6659
6660 // Insert new element into the heap (sift up).
6661 heap[heapSize].currentPointerIndex = currentPointerIndex;
6662 heap[heapSize].lastPointerIndex = lastPointerIndex;
6663 heap[heapSize].distance = distance;
6664 heapSize += 1;
6665 }
6666 }
6667 }
6668
6669 // Heapify
6670 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6671 startIndex -= 1;
6672 for (uint32_t parentIndex = startIndex; ;) {
6673 uint32_t childIndex = parentIndex * 2 + 1;
6674 if (childIndex >= heapSize) {
6675 break;
6676 }
6677
6678 if (childIndex + 1 < heapSize
6679 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6680 childIndex += 1;
6681 }
6682
6683 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6684 break;
6685 }
6686
6687 swap(heap[parentIndex], heap[childIndex]);
6688 parentIndex = childIndex;
6689 }
6690 }
6691
6692#if DEBUG_POINTER_ASSIGNMENT
6693 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6694 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006695 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006696 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6697 heap[i].distance);
6698 }
6699#endif
6700
6701 // Pull matches out by increasing order of distance.
6702 // To avoid reassigning pointers that have already been matched, the loop keeps track
6703 // of which last and current pointers have been matched using the matchedXXXBits variables.
6704 // It also tracks the used pointer id bits.
6705 BitSet32 matchedLastBits(0);
6706 BitSet32 matchedCurrentBits(0);
6707 BitSet32 usedIdBits(0);
6708 bool first = true;
6709 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6710 while (heapSize > 0) {
6711 if (first) {
6712 // The first time through the loop, we just consume the root element of
6713 // the heap (the one with smallest distance).
6714 first = false;
6715 } else {
6716 // Previous iterations consumed the root element of the heap.
6717 // Pop root element off of the heap (sift down).
6718 heap[0] = heap[heapSize];
6719 for (uint32_t parentIndex = 0; ;) {
6720 uint32_t childIndex = parentIndex * 2 + 1;
6721 if (childIndex >= heapSize) {
6722 break;
6723 }
6724
6725 if (childIndex + 1 < heapSize
6726 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6727 childIndex += 1;
6728 }
6729
6730 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6731 break;
6732 }
6733
6734 swap(heap[parentIndex], heap[childIndex]);
6735 parentIndex = childIndex;
6736 }
6737
6738#if DEBUG_POINTER_ASSIGNMENT
6739 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6740 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006741 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006742 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6743 heap[i].distance);
6744 }
6745#endif
6746 }
6747
6748 heapSize -= 1;
6749
6750 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6751 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6752
6753 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6754 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6755
6756 matchedCurrentBits.markBit(currentPointerIndex);
6757 matchedLastBits.markBit(lastPointerIndex);
6758
Michael Wright842500e2015-03-13 17:32:02 -07006759 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6760 current->rawPointerData.pointers[currentPointerIndex].id = id;
6761 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6762 current->rawPointerData.markIdBit(id,
6763 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006764 usedIdBits.markBit(id);
6765
6766#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006767 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6768 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006769 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6770#endif
6771 break;
6772 }
6773 }
6774
6775 // Assign fresh ids to pointers that were not matched in the process.
6776 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6777 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6778 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6779
Michael Wright842500e2015-03-13 17:32:02 -07006780 current->rawPointerData.pointers[currentPointerIndex].id = id;
6781 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6782 current->rawPointerData.markIdBit(id,
6783 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006784
6785#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006786 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006787#endif
6788 }
6789}
6790
6791int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6792 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6793 return AKEY_STATE_VIRTUAL;
6794 }
6795
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006796 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006797 if (virtualKey.keyCode == keyCode) {
6798 return AKEY_STATE_UP;
6799 }
6800 }
6801
6802 return AKEY_STATE_UNKNOWN;
6803}
6804
6805int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6806 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6807 return AKEY_STATE_VIRTUAL;
6808 }
6809
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006810 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006811 if (virtualKey.scanCode == scanCode) {
6812 return AKEY_STATE_UP;
6813 }
6814 }
6815
6816 return AKEY_STATE_UNKNOWN;
6817}
6818
6819bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6820 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006821 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006822 for (size_t i = 0; i < numCodes; i++) {
6823 if (virtualKey.keyCode == keyCodes[i]) {
6824 outFlags[i] = 1;
6825 }
6826 }
6827 }
6828
6829 return true;
6830}
6831
Arthur Hungc23540e2018-11-29 20:42:11 +08006832std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6833 if (mParameters.hasAssociatedDisplay) {
6834 if (mDeviceMode == DEVICE_MODE_POINTER) {
6835 return std::make_optional(mPointerController->getDisplayId());
6836 } else {
6837 return std::make_optional(mViewport.displayId);
6838 }
6839 }
6840 return std::nullopt;
6841}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006842
6843// --- SingleTouchInputMapper ---
6844
6845SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6846 TouchInputMapper(device) {
6847}
6848
6849SingleTouchInputMapper::~SingleTouchInputMapper() {
6850}
6851
6852void SingleTouchInputMapper::reset(nsecs_t when) {
6853 mSingleTouchMotionAccumulator.reset(getDevice());
6854
6855 TouchInputMapper::reset(when);
6856}
6857
6858void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6859 TouchInputMapper::process(rawEvent);
6860
6861 mSingleTouchMotionAccumulator.process(rawEvent);
6862}
6863
Michael Wright842500e2015-03-13 17:32:02 -07006864void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006865 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006866 outState->rawPointerData.pointerCount = 1;
6867 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006868
6869 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6870 && (mTouchButtonAccumulator.isHovering()
6871 || (mRawPointerAxes.pressure.valid
6872 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006873 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006874
Michael Wright842500e2015-03-13 17:32:02 -07006875 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006876 outPointer.id = 0;
6877 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6878 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6879 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6880 outPointer.touchMajor = 0;
6881 outPointer.touchMinor = 0;
6882 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6883 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6884 outPointer.orientation = 0;
6885 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6886 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6887 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6888 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6889 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6890 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6891 }
6892 outPointer.isHovering = isHovering;
6893 }
6894}
6895
6896void SingleTouchInputMapper::configureRawPointerAxes() {
6897 TouchInputMapper::configureRawPointerAxes();
6898
6899 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6900 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6901 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6902 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6903 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6904 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6905 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6906}
6907
6908bool SingleTouchInputMapper::hasStylus() const {
6909 return mTouchButtonAccumulator.hasStylus();
6910}
6911
6912
6913// --- MultiTouchInputMapper ---
6914
6915MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6916 TouchInputMapper(device) {
6917}
6918
6919MultiTouchInputMapper::~MultiTouchInputMapper() {
6920}
6921
6922void MultiTouchInputMapper::reset(nsecs_t when) {
6923 mMultiTouchMotionAccumulator.reset(getDevice());
6924
6925 mPointerIdBits.clear();
6926
6927 TouchInputMapper::reset(when);
6928}
6929
6930void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6931 TouchInputMapper::process(rawEvent);
6932
6933 mMultiTouchMotionAccumulator.process(rawEvent);
6934}
6935
Michael Wright842500e2015-03-13 17:32:02 -07006936void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006937 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6938 size_t outCount = 0;
6939 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006940 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006941
6942 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6943 const MultiTouchMotionAccumulator::Slot* inSlot =
6944 mMultiTouchMotionAccumulator.getSlot(inIndex);
6945 if (!inSlot->isInUse()) {
6946 continue;
6947 }
6948
6949 if (outCount >= MAX_POINTERS) {
6950#if DEBUG_POINTERS
6951 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6952 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006953 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006954#endif
6955 break; // too many fingers!
6956 }
6957
Michael Wright842500e2015-03-13 17:32:02 -07006958 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006959 outPointer.x = inSlot->getX();
6960 outPointer.y = inSlot->getY();
6961 outPointer.pressure = inSlot->getPressure();
6962 outPointer.touchMajor = inSlot->getTouchMajor();
6963 outPointer.touchMinor = inSlot->getTouchMinor();
6964 outPointer.toolMajor = inSlot->getToolMajor();
6965 outPointer.toolMinor = inSlot->getToolMinor();
6966 outPointer.orientation = inSlot->getOrientation();
6967 outPointer.distance = inSlot->getDistance();
6968 outPointer.tiltX = 0;
6969 outPointer.tiltY = 0;
6970
6971 outPointer.toolType = inSlot->getToolType();
6972 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6973 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6974 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6975 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6976 }
6977 }
6978
6979 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6980 && (mTouchButtonAccumulator.isHovering()
6981 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6982 outPointer.isHovering = isHovering;
6983
6984 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006985 if (mHavePointerIds) {
6986 int32_t trackingId = inSlot->getTrackingId();
6987 int32_t id = -1;
6988 if (trackingId >= 0) {
6989 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6990 uint32_t n = idBits.clearFirstMarkedBit();
6991 if (mPointerTrackingIdMap[n] == trackingId) {
6992 id = n;
6993 }
6994 }
6995
6996 if (id < 0 && !mPointerIdBits.isFull()) {
6997 id = mPointerIdBits.markFirstUnmarkedBit();
6998 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006999 }
Michael Wright842500e2015-03-13 17:32:02 -07007000 }
gaoshang1a632de2016-08-24 10:23:50 +08007001 if (id < 0) {
7002 mHavePointerIds = false;
7003 outState->rawPointerData.clearIdBits();
7004 newPointerIdBits.clear();
7005 } else {
7006 outPointer.id = id;
7007 outState->rawPointerData.idToIndex[id] = outCount;
7008 outState->rawPointerData.markIdBit(id, isHovering);
7009 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007010 }
Michael Wright842500e2015-03-13 17:32:02 -07007011 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007012 outCount += 1;
7013 }
7014
Michael Wright842500e2015-03-13 17:32:02 -07007015 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007016 mPointerIdBits = newPointerIdBits;
7017
7018 mMultiTouchMotionAccumulator.finishSync();
7019}
7020
7021void MultiTouchInputMapper::configureRawPointerAxes() {
7022 TouchInputMapper::configureRawPointerAxes();
7023
7024 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7025 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7026 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7027 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7028 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7029 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7030 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7031 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7032 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7033 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7034 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7035
7036 if (mRawPointerAxes.trackingId.valid
7037 && mRawPointerAxes.slot.valid
7038 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7039 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7040 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007041 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7042 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007043 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007044 slotCount = MAX_SLOTS;
7045 }
7046 mMultiTouchMotionAccumulator.configure(getDevice(),
7047 slotCount, true /*usingSlotsProtocol*/);
7048 } else {
7049 mMultiTouchMotionAccumulator.configure(getDevice(),
7050 MAX_POINTERS, false /*usingSlotsProtocol*/);
7051 }
7052}
7053
7054bool MultiTouchInputMapper::hasStylus() const {
7055 return mMultiTouchMotionAccumulator.hasStylus()
7056 || mTouchButtonAccumulator.hasStylus();
7057}
7058
Michael Wright842500e2015-03-13 17:32:02 -07007059// --- ExternalStylusInputMapper
7060
7061ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7062 InputMapper(device) {
7063
7064}
7065
7066uint32_t ExternalStylusInputMapper::getSources() {
7067 return AINPUT_SOURCE_STYLUS;
7068}
7069
7070void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7071 InputMapper::populateDeviceInfo(info);
7072 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7073 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7074}
7075
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007076void ExternalStylusInputMapper::dump(std::string& dump) {
7077 dump += INDENT2 "External Stylus Input Mapper:\n";
7078 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007079 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007080 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007081 dumpStylusState(dump, mStylusState);
7082}
7083
7084void ExternalStylusInputMapper::configure(nsecs_t when,
7085 const InputReaderConfiguration* config, uint32_t changes) {
7086 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7087 mTouchButtonAccumulator.configure(getDevice());
7088}
7089
7090void ExternalStylusInputMapper::reset(nsecs_t when) {
7091 InputDevice* device = getDevice();
7092 mSingleTouchMotionAccumulator.reset(device);
7093 mTouchButtonAccumulator.reset(device);
7094 InputMapper::reset(when);
7095}
7096
7097void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7098 mSingleTouchMotionAccumulator.process(rawEvent);
7099 mTouchButtonAccumulator.process(rawEvent);
7100
7101 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7102 sync(rawEvent->when);
7103 }
7104}
7105
7106void ExternalStylusInputMapper::sync(nsecs_t when) {
7107 mStylusState.clear();
7108
7109 mStylusState.when = when;
7110
Michael Wright45ccacf2015-04-21 19:01:58 +01007111 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7112 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7113 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7114 }
7115
Michael Wright842500e2015-03-13 17:32:02 -07007116 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7117 if (mRawPressureAxis.valid) {
7118 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7119 } else if (mTouchButtonAccumulator.isToolActive()) {
7120 mStylusState.pressure = 1.0f;
7121 } else {
7122 mStylusState.pressure = 0.0f;
7123 }
7124
7125 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007126
7127 mContext->dispatchExternalStylusState(mStylusState);
7128}
7129
Michael Wrightd02c5b62014-02-10 15:10:22 -08007130
7131// --- JoystickInputMapper ---
7132
7133JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7134 InputMapper(device) {
7135}
7136
7137JoystickInputMapper::~JoystickInputMapper() {
7138}
7139
7140uint32_t JoystickInputMapper::getSources() {
7141 return AINPUT_SOURCE_JOYSTICK;
7142}
7143
7144void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7145 InputMapper::populateDeviceInfo(info);
7146
7147 for (size_t i = 0; i < mAxes.size(); i++) {
7148 const Axis& axis = mAxes.valueAt(i);
7149 addMotionRange(axis.axisInfo.axis, axis, info);
7150
7151 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7152 addMotionRange(axis.axisInfo.highAxis, axis, info);
7153
7154 }
7155 }
7156}
7157
7158void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7159 InputDeviceInfo* info) {
7160 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7161 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7162 /* In order to ease the transition for developers from using the old axes
7163 * to the newer, more semantically correct axes, we'll continue to register
7164 * the old axes as duplicates of their corresponding new ones. */
7165 int32_t compatAxis = getCompatAxis(axisId);
7166 if (compatAxis >= 0) {
7167 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7168 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7169 }
7170}
7171
7172/* A mapping from axes the joystick actually has to the axes that should be
7173 * artificially created for compatibility purposes.
7174 * Returns -1 if no compatibility axis is needed. */
7175int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7176 switch(axis) {
7177 case AMOTION_EVENT_AXIS_LTRIGGER:
7178 return AMOTION_EVENT_AXIS_BRAKE;
7179 case AMOTION_EVENT_AXIS_RTRIGGER:
7180 return AMOTION_EVENT_AXIS_GAS;
7181 }
7182 return -1;
7183}
7184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007185void JoystickInputMapper::dump(std::string& dump) {
7186 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007187
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007188 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007189 size_t numAxes = mAxes.size();
7190 for (size_t i = 0; i < numAxes; i++) {
7191 const Axis& axis = mAxes.valueAt(i);
7192 const char* label = getAxisLabel(axis.axisInfo.axis);
7193 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007194 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007195 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007196 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007197 }
7198 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7199 label = getAxisLabel(axis.axisInfo.highAxis);
7200 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007201 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007202 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007203 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007204 axis.axisInfo.splitValue);
7205 }
7206 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007207 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007208 }
7209
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007210 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 -08007211 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007212 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007213 "highScale=%0.5f, highOffset=%0.5f\n",
7214 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007215 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007216 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7217 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7218 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7219 }
7220}
7221
7222void JoystickInputMapper::configure(nsecs_t when,
7223 const InputReaderConfiguration* config, uint32_t changes) {
7224 InputMapper::configure(when, config, changes);
7225
7226 if (!changes) { // first time only
7227 // Collect all axes.
7228 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7229 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7230 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7231 continue; // axis must be claimed by a different device
7232 }
7233
7234 RawAbsoluteAxisInfo rawAxisInfo;
7235 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7236 if (rawAxisInfo.valid) {
7237 // Map axis.
7238 AxisInfo axisInfo;
7239 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7240 if (!explicitlyMapped) {
7241 // Axis is not explicitly mapped, will choose a generic axis later.
7242 axisInfo.mode = AxisInfo::MODE_NORMAL;
7243 axisInfo.axis = -1;
7244 }
7245
7246 // Apply flat override.
7247 int32_t rawFlat = axisInfo.flatOverride < 0
7248 ? rawAxisInfo.flat : axisInfo.flatOverride;
7249
7250 // Calculate scaling factors and limits.
7251 Axis axis;
7252 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7253 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7254 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7255 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7256 scale, 0.0f, highScale, 0.0f,
7257 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7258 rawAxisInfo.resolution * scale);
7259 } else if (isCenteredAxis(axisInfo.axis)) {
7260 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7261 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7262 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7263 scale, offset, scale, offset,
7264 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7265 rawAxisInfo.resolution * scale);
7266 } else {
7267 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7268 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7269 scale, 0.0f, scale, 0.0f,
7270 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7271 rawAxisInfo.resolution * scale);
7272 }
7273
7274 // To eliminate noise while the joystick is at rest, filter out small variations
7275 // in axis values up front.
7276 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7277
7278 mAxes.add(abs, axis);
7279 }
7280 }
7281
7282 // If there are too many axes, start dropping them.
7283 // Prefer to keep explicitly mapped axes.
7284 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007285 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007286 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007287 pruneAxes(true);
7288 pruneAxes(false);
7289 }
7290
7291 // Assign generic axis ids to remaining axes.
7292 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7293 size_t numAxes = mAxes.size();
7294 for (size_t i = 0; i < numAxes; i++) {
7295 Axis& axis = mAxes.editValueAt(i);
7296 if (axis.axisInfo.axis < 0) {
7297 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7298 && haveAxis(nextGenericAxisId)) {
7299 nextGenericAxisId += 1;
7300 }
7301
7302 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7303 axis.axisInfo.axis = nextGenericAxisId;
7304 nextGenericAxisId += 1;
7305 } else {
7306 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7307 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007308 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007309 mAxes.removeItemsAt(i--);
7310 numAxes -= 1;
7311 }
7312 }
7313 }
7314 }
7315}
7316
7317bool JoystickInputMapper::haveAxis(int32_t axisId) {
7318 size_t numAxes = mAxes.size();
7319 for (size_t i = 0; i < numAxes; i++) {
7320 const Axis& axis = mAxes.valueAt(i);
7321 if (axis.axisInfo.axis == axisId
7322 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7323 && axis.axisInfo.highAxis == axisId)) {
7324 return true;
7325 }
7326 }
7327 return false;
7328}
7329
7330void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7331 size_t i = mAxes.size();
7332 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7333 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7334 continue;
7335 }
7336 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007337 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007338 mAxes.removeItemsAt(i);
7339 }
7340}
7341
7342bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7343 switch (axis) {
7344 case AMOTION_EVENT_AXIS_X:
7345 case AMOTION_EVENT_AXIS_Y:
7346 case AMOTION_EVENT_AXIS_Z:
7347 case AMOTION_EVENT_AXIS_RX:
7348 case AMOTION_EVENT_AXIS_RY:
7349 case AMOTION_EVENT_AXIS_RZ:
7350 case AMOTION_EVENT_AXIS_HAT_X:
7351 case AMOTION_EVENT_AXIS_HAT_Y:
7352 case AMOTION_EVENT_AXIS_ORIENTATION:
7353 case AMOTION_EVENT_AXIS_RUDDER:
7354 case AMOTION_EVENT_AXIS_WHEEL:
7355 return true;
7356 default:
7357 return false;
7358 }
7359}
7360
7361void JoystickInputMapper::reset(nsecs_t when) {
7362 // Recenter all axes.
7363 size_t numAxes = mAxes.size();
7364 for (size_t i = 0; i < numAxes; i++) {
7365 Axis& axis = mAxes.editValueAt(i);
7366 axis.resetValue();
7367 }
7368
7369 InputMapper::reset(when);
7370}
7371
7372void JoystickInputMapper::process(const RawEvent* rawEvent) {
7373 switch (rawEvent->type) {
7374 case EV_ABS: {
7375 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7376 if (index >= 0) {
7377 Axis& axis = mAxes.editValueAt(index);
7378 float newValue, highNewValue;
7379 switch (axis.axisInfo.mode) {
7380 case AxisInfo::MODE_INVERT:
7381 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7382 * axis.scale + axis.offset;
7383 highNewValue = 0.0f;
7384 break;
7385 case AxisInfo::MODE_SPLIT:
7386 if (rawEvent->value < axis.axisInfo.splitValue) {
7387 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7388 * axis.scale + axis.offset;
7389 highNewValue = 0.0f;
7390 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7391 newValue = 0.0f;
7392 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7393 * axis.highScale + axis.highOffset;
7394 } else {
7395 newValue = 0.0f;
7396 highNewValue = 0.0f;
7397 }
7398 break;
7399 default:
7400 newValue = rawEvent->value * axis.scale + axis.offset;
7401 highNewValue = 0.0f;
7402 break;
7403 }
7404 axis.newValue = newValue;
7405 axis.highNewValue = highNewValue;
7406 }
7407 break;
7408 }
7409
7410 case EV_SYN:
7411 switch (rawEvent->code) {
7412 case SYN_REPORT:
7413 sync(rawEvent->when, false /*force*/);
7414 break;
7415 }
7416 break;
7417 }
7418}
7419
7420void JoystickInputMapper::sync(nsecs_t when, bool force) {
7421 if (!filterAxes(force)) {
7422 return;
7423 }
7424
7425 int32_t metaState = mContext->getGlobalMetaState();
7426 int32_t buttonState = 0;
7427
7428 PointerProperties pointerProperties;
7429 pointerProperties.clear();
7430 pointerProperties.id = 0;
7431 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7432
7433 PointerCoords pointerCoords;
7434 pointerCoords.clear();
7435
7436 size_t numAxes = mAxes.size();
7437 for (size_t i = 0; i < numAxes; i++) {
7438 const Axis& axis = mAxes.valueAt(i);
7439 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7440 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7441 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7442 axis.highCurrentValue);
7443 }
7444 }
7445
7446 // Moving a joystick axis should not wake the device because joysticks can
7447 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7448 // button will likely wake the device.
7449 // TODO: Use the input device configuration to control this behavior more finely.
7450 uint32_t policyFlags = 0;
7451
Prabir Pradhan42611e02018-11-27 14:04:02 -08007452 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007453 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7454 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07007455 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
7456 &pointerProperties, &pointerCoords, 0, 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07007457 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7458 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007459 getListener()->notifyMotion(&args);
7460}
7461
7462void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7463 int32_t axis, float value) {
7464 pointerCoords->setAxisValue(axis, value);
7465 /* In order to ease the transition for developers from using the old axes
7466 * to the newer, more semantically correct axes, we'll continue to produce
7467 * values for the old axes as mirrors of the value of their corresponding
7468 * new axes. */
7469 int32_t compatAxis = getCompatAxis(axis);
7470 if (compatAxis >= 0) {
7471 pointerCoords->setAxisValue(compatAxis, value);
7472 }
7473}
7474
7475bool JoystickInputMapper::filterAxes(bool force) {
7476 bool atLeastOneSignificantChange = force;
7477 size_t numAxes = mAxes.size();
7478 for (size_t i = 0; i < numAxes; i++) {
7479 Axis& axis = mAxes.editValueAt(i);
7480 if (force || hasValueChangedSignificantly(axis.filter,
7481 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7482 axis.currentValue = axis.newValue;
7483 atLeastOneSignificantChange = true;
7484 }
7485 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7486 if (force || hasValueChangedSignificantly(axis.filter,
7487 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7488 axis.highCurrentValue = axis.highNewValue;
7489 atLeastOneSignificantChange = true;
7490 }
7491 }
7492 }
7493 return atLeastOneSignificantChange;
7494}
7495
7496bool JoystickInputMapper::hasValueChangedSignificantly(
7497 float filter, float newValue, float currentValue, float min, float max) {
7498 if (newValue != currentValue) {
7499 // Filter out small changes in value unless the value is converging on the axis
7500 // bounds or center point. This is intended to reduce the amount of information
7501 // sent to applications by particularly noisy joysticks (such as PS3).
7502 if (fabs(newValue - currentValue) > filter
7503 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7504 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7505 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7506 return true;
7507 }
7508 }
7509 return false;
7510}
7511
7512bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7513 float filter, float newValue, float currentValue, float thresholdValue) {
7514 float newDistance = fabs(newValue - thresholdValue);
7515 if (newDistance < filter) {
7516 float oldDistance = fabs(currentValue - thresholdValue);
7517 if (newDistance < oldDistance) {
7518 return true;
7519 }
7520 }
7521 return false;
7522}
7523
7524} // namespace android