blob: 21ba0298542d02af4718078b9200509b3ab8a777 [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;
290 Vector<InputDeviceInfo> inputDevices;
291 { // 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
593void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
594 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()) {
597 outDevices.push();
598 device->getDeviceInfo(&outDevices.editTop());
599 }
600 }
601}
602
603void InputReader::dispatchExternalStylusState(const StylusState& state) {
604 for (size_t i = 0; i < mDevices.size(); i++) {
605 InputDevice* device = mDevices.valueAt(i);
606 device->updateExternalStylusState(state);
607 }
608}
609
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
611 mDisableVirtualKeysTimeout = time;
612}
613
614bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
615 InputDevice* device, int32_t keyCode, int32_t scanCode) {
616 if (now < mDisableVirtualKeysTimeout) {
617 ALOGI("Dropping virtual key from device %s because virtual keys are "
618 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100619 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800620 (mDisableVirtualKeysTimeout - now) * 0.000001,
621 keyCode, scanCode);
622 return true;
623 } else {
624 return false;
625 }
626}
627
628void InputReader::fadePointerLocked() {
629 for (size_t i = 0; i < mDevices.size(); i++) {
630 InputDevice* device = mDevices.valueAt(i);
631 device->fadePointer();
632 }
633}
634
635void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
636 if (when < mNextTimeout) {
637 mNextTimeout = when;
638 mEventHub->wake();
639 }
640}
641
642int32_t InputReader::bumpGenerationLocked() {
643 return ++mGeneration;
644}
645
646void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
647 AutoMutex _l(mLock);
648 getInputDevicesLocked(outInputDevices);
649}
650
651void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
652 outInputDevices.clear();
653
654 size_t numDevices = mDevices.size();
655 for (size_t i = 0; i < numDevices; i++) {
656 InputDevice* device = mDevices.valueAt(i);
657 if (!device->isIgnored()) {
658 outInputDevices.push();
659 device->getDeviceInfo(&outInputDevices.editTop());
660 }
661 }
662}
663
664int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
665 int32_t keyCode) {
666 AutoMutex _l(mLock);
667
668 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
669}
670
671int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
672 int32_t scanCode) {
673 AutoMutex _l(mLock);
674
675 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
676}
677
678int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
679 AutoMutex _l(mLock);
680
681 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
682}
683
684int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
685 GetStateFunc getStateFunc) {
686 int32_t result = AKEY_STATE_UNKNOWN;
687 if (deviceId >= 0) {
688 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
689 if (deviceIndex >= 0) {
690 InputDevice* device = mDevices.valueAt(deviceIndex);
691 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
692 result = (device->*getStateFunc)(sourceMask, code);
693 }
694 }
695 } else {
696 size_t numDevices = mDevices.size();
697 for (size_t i = 0; i < numDevices; i++) {
698 InputDevice* device = mDevices.valueAt(i);
699 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
700 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
701 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
702 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
703 if (currentResult >= AKEY_STATE_DOWN) {
704 return currentResult;
705 } else if (currentResult == AKEY_STATE_UP) {
706 result = currentResult;
707 }
708 }
709 }
710 }
711 return result;
712}
713
Andrii Kulian763a3a42016-03-08 10:46:16 -0800714void InputReader::toggleCapsLockState(int32_t deviceId) {
715 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
716 if (deviceIndex < 0) {
717 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
718 return;
719 }
720
721 InputDevice* device = mDevices.valueAt(deviceIndex);
722 if (device->isIgnored()) {
723 return;
724 }
725
726 device->updateMetaState(AKEYCODE_CAPS_LOCK);
727}
728
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
730 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
731 AutoMutex _l(mLock);
732
733 memset(outFlags, 0, numCodes);
734 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
735}
736
737bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
738 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
739 bool result = false;
740 if (deviceId >= 0) {
741 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
742 if (deviceIndex >= 0) {
743 InputDevice* device = mDevices.valueAt(deviceIndex);
744 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
745 result = device->markSupportedKeyCodes(sourceMask,
746 numCodes, keyCodes, outFlags);
747 }
748 }
749 } else {
750 size_t numDevices = mDevices.size();
751 for (size_t i = 0; i < numDevices; i++) {
752 InputDevice* device = mDevices.valueAt(i);
753 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
754 result |= device->markSupportedKeyCodes(sourceMask,
755 numCodes, keyCodes, outFlags);
756 }
757 }
758 }
759 return result;
760}
761
762void InputReader::requestRefreshConfiguration(uint32_t changes) {
763 AutoMutex _l(mLock);
764
765 if (changes) {
766 bool needWake = !mConfigurationChangesToRefresh;
767 mConfigurationChangesToRefresh |= changes;
768
769 if (needWake) {
770 mEventHub->wake();
771 }
772 }
773}
774
775void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
776 ssize_t repeat, int32_t token) {
777 AutoMutex _l(mLock);
778
779 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
780 if (deviceIndex >= 0) {
781 InputDevice* device = mDevices.valueAt(deviceIndex);
782 device->vibrate(pattern, patternSize, repeat, token);
783 }
784}
785
786void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
787 AutoMutex _l(mLock);
788
789 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
790 if (deviceIndex >= 0) {
791 InputDevice* device = mDevices.valueAt(deviceIndex);
792 device->cancelVibrate(token);
793 }
794}
795
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700796bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
797 AutoMutex _l(mLock);
798
799 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
800 if (deviceIndex >= 0) {
801 InputDevice* device = mDevices.valueAt(deviceIndex);
802 return device->isEnabled();
803 }
804 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
805 return false;
806}
807
Arthur Hungc23540e2018-11-29 20:42:11 +0800808bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
809 AutoMutex _l(mLock);
810
811 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
812 if (deviceIndex < 0) {
813 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
814 return false;
815 }
816
817 InputDevice* device = mDevices.valueAt(deviceIndex);
818 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
819 // No associated display. By default, can dispatch to all displays.
820 if (!associatedDisplayId) {
821 return true;
822 }
823
824 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
825 ALOGW("Device has associated, but no associated display id.");
826 return true;
827 }
828
829 return *associatedDisplayId == displayId;
830}
831
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800832void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 AutoMutex _l(mLock);
834
835 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800836 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800838 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
840 for (size_t i = 0; i < mDevices.size(); i++) {
841 mDevices.valueAt(i)->dump(dump);
842 }
843
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800844 dump += INDENT "Configuration:\n";
845 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
847 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800848 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100850 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += "]\n";
853 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 mConfig.virtualKeyQuietTime * 0.000001f);
855
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
858 mConfig.pointerVelocityControlParameters.scale,
859 mConfig.pointerVelocityControlParameters.lowThreshold,
860 mConfig.pointerVelocityControlParameters.highThreshold,
861 mConfig.pointerVelocityControlParameters.acceleration);
862
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800863 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
865 mConfig.wheelVelocityControlParameters.scale,
866 mConfig.wheelVelocityControlParameters.lowThreshold,
867 mConfig.wheelVelocityControlParameters.highThreshold,
868 mConfig.wheelVelocityControlParameters.acceleration);
869
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800870 dump += StringPrintf(INDENT2 "PointerGesture:\n");
871 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800873 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800875 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800876 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800877 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800878 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800879 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800881 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700895
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800896 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700897 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898}
899
900void InputReader::monitor() {
901 // Acquire and release the lock to ensure that the reader has not deadlocked.
902 mLock.lock();
903 mEventHub->wake();
904 mReaderIsAliveCondition.wait(mLock);
905 mLock.unlock();
906
907 // Check the EventHub
908 mEventHub->monitor();
909}
910
911
912// --- InputReader::ContextImpl ---
913
914InputReader::ContextImpl::ContextImpl(InputReader* reader) :
915 mReader(reader) {
916}
917
918void InputReader::ContextImpl::updateGlobalMetaState() {
919 // lock is already held by the input loop
920 mReader->updateGlobalMetaStateLocked();
921}
922
923int32_t InputReader::ContextImpl::getGlobalMetaState() {
924 // lock is already held by the input loop
925 return mReader->getGlobalMetaStateLocked();
926}
927
928void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
929 // lock is already held by the input loop
930 mReader->disableVirtualKeysUntilLocked(time);
931}
932
933bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
934 InputDevice* device, int32_t keyCode, int32_t scanCode) {
935 // lock is already held by the input loop
936 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
937}
938
939void InputReader::ContextImpl::fadePointer() {
940 // lock is already held by the input loop
941 mReader->fadePointerLocked();
942}
943
944void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
945 // lock is already held by the input loop
946 mReader->requestTimeoutAtTimeLocked(when);
947}
948
949int32_t InputReader::ContextImpl::bumpGeneration() {
950 // lock is already held by the input loop
951 return mReader->bumpGenerationLocked();
952}
953
Michael Wright842500e2015-03-13 17:32:02 -0700954void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
955 // lock is already held by whatever called refreshConfigurationLocked
956 mReader->getExternalStylusDevicesLocked(outDevices);
957}
958
959void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
960 mReader->dispatchExternalStylusState(state);
961}
962
Michael Wrightd02c5b62014-02-10 15:10:22 -0800963InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
964 return mReader->mPolicy.get();
965}
966
967InputListenerInterface* InputReader::ContextImpl::getListener() {
968 return mReader->mQueuedListener.get();
969}
970
971EventHubInterface* InputReader::ContextImpl::getEventHub() {
972 return mReader->mEventHub.get();
973}
974
Prabir Pradhan42611e02018-11-27 14:04:02 -0800975uint32_t InputReader::ContextImpl::getNextSequenceNum() {
976 return (mReader->mNextSequenceNum)++;
977}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800978
Michael Wrightd02c5b62014-02-10 15:10:22 -0800979// --- InputDevice ---
980
981InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
982 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
983 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
984 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700985 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986}
987
988InputDevice::~InputDevice() {
989 size_t numMappers = mMappers.size();
990 for (size_t i = 0; i < numMappers; i++) {
991 delete mMappers[i];
992 }
993 mMappers.clear();
994}
995
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700996bool InputDevice::isEnabled() {
997 return getEventHub()->isDeviceEnabled(mId);
998}
999
1000void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1001 if (isEnabled() == enabled) {
1002 return;
1003 }
1004
1005 if (enabled) {
1006 getEventHub()->enableDevice(mId);
1007 reset(when);
1008 } else {
1009 reset(when);
1010 getEventHub()->disableDevice(mId);
1011 }
1012 // Must change generation to flag this device as changed
1013 bumpGeneration();
1014}
1015
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001016void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001017 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001018 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001019
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001020 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001021 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001022 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1023 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001024 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1025 if (mAssociatedDisplayPort) {
1026 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1027 } else {
1028 dump += "<none>\n";
1029 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001030 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1031 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1032 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001033
1034 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1035 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001036 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001037 for (size_t i = 0; i < ranges.size(); i++) {
1038 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1039 const char* label = getAxisLabel(range.axis);
1040 char name[32];
1041 if (label) {
1042 strncpy(name, label, sizeof(name));
1043 name[sizeof(name) - 1] = '\0';
1044 } else {
1045 snprintf(name, sizeof(name), "%d", range.axis);
1046 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001047 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001048 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1049 name, range.source, range.min, range.max, range.flat, range.fuzz,
1050 range.resolution);
1051 }
1052 }
1053
1054 size_t numMappers = mMappers.size();
1055 for (size_t i = 0; i < numMappers; i++) {
1056 InputMapper* mapper = mMappers[i];
1057 mapper->dump(dump);
1058 }
1059}
1060
1061void InputDevice::addMapper(InputMapper* mapper) {
1062 mMappers.add(mapper);
1063}
1064
1065void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1066 mSources = 0;
1067
1068 if (!isIgnored()) {
1069 if (!changes) { // first time only
1070 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1071 }
1072
1073 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1074 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1075 sp<KeyCharacterMap> keyboardLayout =
1076 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1077 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1078 bumpGeneration();
1079 }
1080 }
1081 }
1082
1083 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1084 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001085 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 if (mAlias != alias) {
1087 mAlias = alias;
1088 bumpGeneration();
1089 }
1090 }
1091 }
1092
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001093 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1094 ssize_t index = config->disabledDevices.indexOf(mId);
1095 bool enabled = index < 0;
1096 setEnabled(enabled, when);
1097 }
1098
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001099 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1100 // In most situations, no port will be specified.
1101 mAssociatedDisplayPort = std::nullopt;
1102 // Find the display port that corresponds to the current input port.
1103 const std::string& inputPort = mIdentifier.location;
1104 if (!inputPort.empty()) {
1105 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1106 const auto& displayPort = ports.find(inputPort);
1107 if (displayPort != ports.end()) {
1108 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1109 }
1110 }
1111 }
1112
Michael Wrightd02c5b62014-02-10 15:10:22 -08001113 size_t numMappers = mMappers.size();
1114 for (size_t i = 0; i < numMappers; i++) {
1115 InputMapper* mapper = mMappers[i];
1116 mapper->configure(when, config, changes);
1117 mSources |= mapper->getSources();
1118 }
1119 }
1120}
1121
1122void InputDevice::reset(nsecs_t when) {
1123 size_t numMappers = mMappers.size();
1124 for (size_t i = 0; i < numMappers; i++) {
1125 InputMapper* mapper = mMappers[i];
1126 mapper->reset(when);
1127 }
1128
1129 mContext->updateGlobalMetaState();
1130
1131 notifyReset(when);
1132}
1133
1134void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1135 // Process all of the events in order for each mapper.
1136 // We cannot simply ask each mapper to process them in bulk because mappers may
1137 // have side-effects that must be interleaved. For example, joystick movement events and
1138 // gamepad button presses are handled by different mappers but they should be dispatched
1139 // in the order received.
1140 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001141 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001143 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001144 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1145 rawEvent->when);
1146#endif
1147
1148 if (mDropUntilNextSync) {
1149 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1150 mDropUntilNextSync = false;
1151#if DEBUG_RAW_EVENTS
1152 ALOGD("Recovered from input event buffer overrun.");
1153#endif
1154 } else {
1155#if DEBUG_RAW_EVENTS
1156 ALOGD("Dropped input event while waiting for next input sync.");
1157#endif
1158 }
1159 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001160 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161 mDropUntilNextSync = true;
1162 reset(rawEvent->when);
1163 } else {
1164 for (size_t i = 0; i < numMappers; i++) {
1165 InputMapper* mapper = mMappers[i];
1166 mapper->process(rawEvent);
1167 }
1168 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001169 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001170 }
1171}
1172
1173void InputDevice::timeoutExpired(nsecs_t when) {
1174 size_t numMappers = mMappers.size();
1175 for (size_t i = 0; i < numMappers; i++) {
1176 InputMapper* mapper = mMappers[i];
1177 mapper->timeoutExpired(when);
1178 }
1179}
1180
Michael Wright842500e2015-03-13 17:32:02 -07001181void InputDevice::updateExternalStylusState(const StylusState& state) {
1182 size_t numMappers = mMappers.size();
1183 for (size_t i = 0; i < numMappers; i++) {
1184 InputMapper* mapper = mMappers[i];
1185 mapper->updateExternalStylusState(state);
1186 }
1187}
1188
Michael Wrightd02c5b62014-02-10 15:10:22 -08001189void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1190 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001191 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001192 size_t numMappers = mMappers.size();
1193 for (size_t i = 0; i < numMappers; i++) {
1194 InputMapper* mapper = mMappers[i];
1195 mapper->populateDeviceInfo(outDeviceInfo);
1196 }
1197}
1198
1199int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1200 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1201}
1202
1203int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1204 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1205}
1206
1207int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1208 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1209}
1210
1211int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1212 int32_t result = AKEY_STATE_UNKNOWN;
1213 size_t numMappers = mMappers.size();
1214 for (size_t i = 0; i < numMappers; i++) {
1215 InputMapper* mapper = mMappers[i];
1216 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1217 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1218 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1219 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1220 if (currentResult >= AKEY_STATE_DOWN) {
1221 return currentResult;
1222 } else if (currentResult == AKEY_STATE_UP) {
1223 result = currentResult;
1224 }
1225 }
1226 }
1227 return result;
1228}
1229
1230bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1231 const int32_t* keyCodes, uint8_t* outFlags) {
1232 bool result = false;
1233 size_t numMappers = mMappers.size();
1234 for (size_t i = 0; i < numMappers; i++) {
1235 InputMapper* mapper = mMappers[i];
1236 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1237 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1238 }
1239 }
1240 return result;
1241}
1242
1243void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1244 int32_t token) {
1245 size_t numMappers = mMappers.size();
1246 for (size_t i = 0; i < numMappers; i++) {
1247 InputMapper* mapper = mMappers[i];
1248 mapper->vibrate(pattern, patternSize, repeat, token);
1249 }
1250}
1251
1252void InputDevice::cancelVibrate(int32_t token) {
1253 size_t numMappers = mMappers.size();
1254 for (size_t i = 0; i < numMappers; i++) {
1255 InputMapper* mapper = mMappers[i];
1256 mapper->cancelVibrate(token);
1257 }
1258}
1259
Jeff Brownc9aa6282015-02-11 19:03:28 -08001260void InputDevice::cancelTouch(nsecs_t when) {
1261 size_t numMappers = mMappers.size();
1262 for (size_t i = 0; i < numMappers; i++) {
1263 InputMapper* mapper = mMappers[i];
1264 mapper->cancelTouch(when);
1265 }
1266}
1267
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268int32_t InputDevice::getMetaState() {
1269 int32_t result = 0;
1270 size_t numMappers = mMappers.size();
1271 for (size_t i = 0; i < numMappers; i++) {
1272 InputMapper* mapper = mMappers[i];
1273 result |= mapper->getMetaState();
1274 }
1275 return result;
1276}
1277
Andrii Kulian763a3a42016-03-08 10:46:16 -08001278void InputDevice::updateMetaState(int32_t keyCode) {
1279 size_t numMappers = mMappers.size();
1280 for (size_t i = 0; i < numMappers; i++) {
1281 mMappers[i]->updateMetaState(keyCode);
1282 }
1283}
1284
Michael Wrightd02c5b62014-02-10 15:10:22 -08001285void InputDevice::fadePointer() {
1286 size_t numMappers = mMappers.size();
1287 for (size_t i = 0; i < numMappers; i++) {
1288 InputMapper* mapper = mMappers[i];
1289 mapper->fadePointer();
1290 }
1291}
1292
1293void InputDevice::bumpGeneration() {
1294 mGeneration = mContext->bumpGeneration();
1295}
1296
1297void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001298 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001299 mContext->getListener()->notifyDeviceReset(&args);
1300}
1301
Arthur Hungc23540e2018-11-29 20:42:11 +08001302std::optional<int32_t> InputDevice::getAssociatedDisplay() {
1303 size_t numMappers = mMappers.size();
1304 for (size_t i = 0; i < numMappers; i++) {
1305 InputMapper* mapper = mMappers[i];
1306 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1307 if (associatedDisplayId) {
1308 return associatedDisplayId;
1309 }
1310 }
1311
1312 return std::nullopt;
1313}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314
1315// --- CursorButtonAccumulator ---
1316
1317CursorButtonAccumulator::CursorButtonAccumulator() {
1318 clearButtons();
1319}
1320
1321void CursorButtonAccumulator::reset(InputDevice* device) {
1322 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1323 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1324 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1325 mBtnBack = device->isKeyPressed(BTN_BACK);
1326 mBtnSide = device->isKeyPressed(BTN_SIDE);
1327 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1328 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1329 mBtnTask = device->isKeyPressed(BTN_TASK);
1330}
1331
1332void CursorButtonAccumulator::clearButtons() {
1333 mBtnLeft = 0;
1334 mBtnRight = 0;
1335 mBtnMiddle = 0;
1336 mBtnBack = 0;
1337 mBtnSide = 0;
1338 mBtnForward = 0;
1339 mBtnExtra = 0;
1340 mBtnTask = 0;
1341}
1342
1343void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1344 if (rawEvent->type == EV_KEY) {
1345 switch (rawEvent->code) {
1346 case BTN_LEFT:
1347 mBtnLeft = rawEvent->value;
1348 break;
1349 case BTN_RIGHT:
1350 mBtnRight = rawEvent->value;
1351 break;
1352 case BTN_MIDDLE:
1353 mBtnMiddle = rawEvent->value;
1354 break;
1355 case BTN_BACK:
1356 mBtnBack = rawEvent->value;
1357 break;
1358 case BTN_SIDE:
1359 mBtnSide = rawEvent->value;
1360 break;
1361 case BTN_FORWARD:
1362 mBtnForward = rawEvent->value;
1363 break;
1364 case BTN_EXTRA:
1365 mBtnExtra = rawEvent->value;
1366 break;
1367 case BTN_TASK:
1368 mBtnTask = rawEvent->value;
1369 break;
1370 }
1371 }
1372}
1373
1374uint32_t CursorButtonAccumulator::getButtonState() const {
1375 uint32_t result = 0;
1376 if (mBtnLeft) {
1377 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1378 }
1379 if (mBtnRight) {
1380 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1381 }
1382 if (mBtnMiddle) {
1383 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1384 }
1385 if (mBtnBack || mBtnSide) {
1386 result |= AMOTION_EVENT_BUTTON_BACK;
1387 }
1388 if (mBtnForward || mBtnExtra) {
1389 result |= AMOTION_EVENT_BUTTON_FORWARD;
1390 }
1391 return result;
1392}
1393
1394
1395// --- CursorMotionAccumulator ---
1396
1397CursorMotionAccumulator::CursorMotionAccumulator() {
1398 clearRelativeAxes();
1399}
1400
1401void CursorMotionAccumulator::reset(InputDevice* device) {
1402 clearRelativeAxes();
1403}
1404
1405void CursorMotionAccumulator::clearRelativeAxes() {
1406 mRelX = 0;
1407 mRelY = 0;
1408}
1409
1410void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1411 if (rawEvent->type == EV_REL) {
1412 switch (rawEvent->code) {
1413 case REL_X:
1414 mRelX = rawEvent->value;
1415 break;
1416 case REL_Y:
1417 mRelY = rawEvent->value;
1418 break;
1419 }
1420 }
1421}
1422
1423void CursorMotionAccumulator::finishSync() {
1424 clearRelativeAxes();
1425}
1426
1427
1428// --- CursorScrollAccumulator ---
1429
1430CursorScrollAccumulator::CursorScrollAccumulator() :
1431 mHaveRelWheel(false), mHaveRelHWheel(false) {
1432 clearRelativeAxes();
1433}
1434
1435void CursorScrollAccumulator::configure(InputDevice* device) {
1436 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1437 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1438}
1439
1440void CursorScrollAccumulator::reset(InputDevice* device) {
1441 clearRelativeAxes();
1442}
1443
1444void CursorScrollAccumulator::clearRelativeAxes() {
1445 mRelWheel = 0;
1446 mRelHWheel = 0;
1447}
1448
1449void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1450 if (rawEvent->type == EV_REL) {
1451 switch (rawEvent->code) {
1452 case REL_WHEEL:
1453 mRelWheel = rawEvent->value;
1454 break;
1455 case REL_HWHEEL:
1456 mRelHWheel = rawEvent->value;
1457 break;
1458 }
1459 }
1460}
1461
1462void CursorScrollAccumulator::finishSync() {
1463 clearRelativeAxes();
1464}
1465
1466
1467// --- TouchButtonAccumulator ---
1468
1469TouchButtonAccumulator::TouchButtonAccumulator() :
1470 mHaveBtnTouch(false), mHaveStylus(false) {
1471 clearButtons();
1472}
1473
1474void TouchButtonAccumulator::configure(InputDevice* device) {
1475 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1476 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1477 || device->hasKey(BTN_TOOL_RUBBER)
1478 || device->hasKey(BTN_TOOL_BRUSH)
1479 || device->hasKey(BTN_TOOL_PENCIL)
1480 || device->hasKey(BTN_TOOL_AIRBRUSH);
1481}
1482
1483void TouchButtonAccumulator::reset(InputDevice* device) {
1484 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1485 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001486 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1487 mBtnStylus2 =
1488 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001489 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1490 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1491 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1492 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1493 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1494 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1495 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1496 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1497 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1498 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1499 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1500}
1501
1502void TouchButtonAccumulator::clearButtons() {
1503 mBtnTouch = 0;
1504 mBtnStylus = 0;
1505 mBtnStylus2 = 0;
1506 mBtnToolFinger = 0;
1507 mBtnToolPen = 0;
1508 mBtnToolRubber = 0;
1509 mBtnToolBrush = 0;
1510 mBtnToolPencil = 0;
1511 mBtnToolAirbrush = 0;
1512 mBtnToolMouse = 0;
1513 mBtnToolLens = 0;
1514 mBtnToolDoubleTap = 0;
1515 mBtnToolTripleTap = 0;
1516 mBtnToolQuadTap = 0;
1517}
1518
1519void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1520 if (rawEvent->type == EV_KEY) {
1521 switch (rawEvent->code) {
1522 case BTN_TOUCH:
1523 mBtnTouch = rawEvent->value;
1524 break;
1525 case BTN_STYLUS:
1526 mBtnStylus = rawEvent->value;
1527 break;
1528 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001529 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001530 mBtnStylus2 = rawEvent->value;
1531 break;
1532 case BTN_TOOL_FINGER:
1533 mBtnToolFinger = rawEvent->value;
1534 break;
1535 case BTN_TOOL_PEN:
1536 mBtnToolPen = rawEvent->value;
1537 break;
1538 case BTN_TOOL_RUBBER:
1539 mBtnToolRubber = rawEvent->value;
1540 break;
1541 case BTN_TOOL_BRUSH:
1542 mBtnToolBrush = rawEvent->value;
1543 break;
1544 case BTN_TOOL_PENCIL:
1545 mBtnToolPencil = rawEvent->value;
1546 break;
1547 case BTN_TOOL_AIRBRUSH:
1548 mBtnToolAirbrush = rawEvent->value;
1549 break;
1550 case BTN_TOOL_MOUSE:
1551 mBtnToolMouse = rawEvent->value;
1552 break;
1553 case BTN_TOOL_LENS:
1554 mBtnToolLens = rawEvent->value;
1555 break;
1556 case BTN_TOOL_DOUBLETAP:
1557 mBtnToolDoubleTap = rawEvent->value;
1558 break;
1559 case BTN_TOOL_TRIPLETAP:
1560 mBtnToolTripleTap = rawEvent->value;
1561 break;
1562 case BTN_TOOL_QUADTAP:
1563 mBtnToolQuadTap = rawEvent->value;
1564 break;
1565 }
1566 }
1567}
1568
1569uint32_t TouchButtonAccumulator::getButtonState() const {
1570 uint32_t result = 0;
1571 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001572 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001573 }
1574 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001575 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001576 }
1577 return result;
1578}
1579
1580int32_t TouchButtonAccumulator::getToolType() const {
1581 if (mBtnToolMouse || mBtnToolLens) {
1582 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1583 }
1584 if (mBtnToolRubber) {
1585 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1586 }
1587 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1588 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1589 }
1590 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1591 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1592 }
1593 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1594}
1595
1596bool TouchButtonAccumulator::isToolActive() const {
1597 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1598 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1599 || mBtnToolMouse || mBtnToolLens
1600 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1601}
1602
1603bool TouchButtonAccumulator::isHovering() const {
1604 return mHaveBtnTouch && !mBtnTouch;
1605}
1606
1607bool TouchButtonAccumulator::hasStylus() const {
1608 return mHaveStylus;
1609}
1610
1611
1612// --- RawPointerAxes ---
1613
1614RawPointerAxes::RawPointerAxes() {
1615 clear();
1616}
1617
1618void RawPointerAxes::clear() {
1619 x.clear();
1620 y.clear();
1621 pressure.clear();
1622 touchMajor.clear();
1623 touchMinor.clear();
1624 toolMajor.clear();
1625 toolMinor.clear();
1626 orientation.clear();
1627 distance.clear();
1628 tiltX.clear();
1629 tiltY.clear();
1630 trackingId.clear();
1631 slot.clear();
1632}
1633
1634
1635// --- RawPointerData ---
1636
1637RawPointerData::RawPointerData() {
1638 clear();
1639}
1640
1641void RawPointerData::clear() {
1642 pointerCount = 0;
1643 clearIdBits();
1644}
1645
1646void RawPointerData::copyFrom(const RawPointerData& other) {
1647 pointerCount = other.pointerCount;
1648 hoveringIdBits = other.hoveringIdBits;
1649 touchingIdBits = other.touchingIdBits;
1650
1651 for (uint32_t i = 0; i < pointerCount; i++) {
1652 pointers[i] = other.pointers[i];
1653
1654 int id = pointers[i].id;
1655 idToIndex[id] = other.idToIndex[id];
1656 }
1657}
1658
1659void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1660 float x = 0, y = 0;
1661 uint32_t count = touchingIdBits.count();
1662 if (count) {
1663 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1664 uint32_t id = idBits.clearFirstMarkedBit();
1665 const Pointer& pointer = pointerForId(id);
1666 x += pointer.x;
1667 y += pointer.y;
1668 }
1669 x /= count;
1670 y /= count;
1671 }
1672 *outX = x;
1673 *outY = y;
1674}
1675
1676
1677// --- CookedPointerData ---
1678
1679CookedPointerData::CookedPointerData() {
1680 clear();
1681}
1682
1683void CookedPointerData::clear() {
1684 pointerCount = 0;
1685 hoveringIdBits.clear();
1686 touchingIdBits.clear();
1687}
1688
1689void CookedPointerData::copyFrom(const CookedPointerData& other) {
1690 pointerCount = other.pointerCount;
1691 hoveringIdBits = other.hoveringIdBits;
1692 touchingIdBits = other.touchingIdBits;
1693
1694 for (uint32_t i = 0; i < pointerCount; i++) {
1695 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1696 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1697
1698 int id = pointerProperties[i].id;
1699 idToIndex[id] = other.idToIndex[id];
1700 }
1701}
1702
1703
1704// --- SingleTouchMotionAccumulator ---
1705
1706SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1707 clearAbsoluteAxes();
1708}
1709
1710void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1711 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1712 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1713 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1714 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1715 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1716 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1717 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1718}
1719
1720void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1721 mAbsX = 0;
1722 mAbsY = 0;
1723 mAbsPressure = 0;
1724 mAbsToolWidth = 0;
1725 mAbsDistance = 0;
1726 mAbsTiltX = 0;
1727 mAbsTiltY = 0;
1728}
1729
1730void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1731 if (rawEvent->type == EV_ABS) {
1732 switch (rawEvent->code) {
1733 case ABS_X:
1734 mAbsX = rawEvent->value;
1735 break;
1736 case ABS_Y:
1737 mAbsY = rawEvent->value;
1738 break;
1739 case ABS_PRESSURE:
1740 mAbsPressure = rawEvent->value;
1741 break;
1742 case ABS_TOOL_WIDTH:
1743 mAbsToolWidth = rawEvent->value;
1744 break;
1745 case ABS_DISTANCE:
1746 mAbsDistance = rawEvent->value;
1747 break;
1748 case ABS_TILT_X:
1749 mAbsTiltX = rawEvent->value;
1750 break;
1751 case ABS_TILT_Y:
1752 mAbsTiltY = rawEvent->value;
1753 break;
1754 }
1755 }
1756}
1757
1758
1759// --- MultiTouchMotionAccumulator ---
1760
1761MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001762 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001763 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001764}
1765
1766MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1767 delete[] mSlots;
1768}
1769
1770void MultiTouchMotionAccumulator::configure(InputDevice* device,
1771 size_t slotCount, bool usingSlotsProtocol) {
1772 mSlotCount = slotCount;
1773 mUsingSlotsProtocol = usingSlotsProtocol;
1774 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1775
1776 delete[] mSlots;
1777 mSlots = new Slot[slotCount];
1778}
1779
1780void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1781 // Unfortunately there is no way to read the initial contents of the slots.
1782 // So when we reset the accumulator, we must assume they are all zeroes.
1783 if (mUsingSlotsProtocol) {
1784 // Query the driver for the current slot index and use it as the initial slot
1785 // before we start reading events from the device. It is possible that the
1786 // current slot index will not be the same as it was when the first event was
1787 // written into the evdev buffer, which means the input mapper could start
1788 // out of sync with the initial state of the events in the evdev buffer.
1789 // In the extremely unlikely case that this happens, the data from
1790 // two slots will be confused until the next ABS_MT_SLOT event is received.
1791 // This can cause the touch point to "jump", but at least there will be
1792 // no stuck touches.
1793 int32_t initialSlot;
1794 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1795 ABS_MT_SLOT, &initialSlot);
1796 if (status) {
1797 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1798 initialSlot = -1;
1799 }
1800 clearSlots(initialSlot);
1801 } else {
1802 clearSlots(-1);
1803 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001804 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001805}
1806
1807void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1808 if (mSlots) {
1809 for (size_t i = 0; i < mSlotCount; i++) {
1810 mSlots[i].clear();
1811 }
1812 }
1813 mCurrentSlot = initialSlot;
1814}
1815
1816void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1817 if (rawEvent->type == EV_ABS) {
1818 bool newSlot = false;
1819 if (mUsingSlotsProtocol) {
1820 if (rawEvent->code == ABS_MT_SLOT) {
1821 mCurrentSlot = rawEvent->value;
1822 newSlot = true;
1823 }
1824 } else if (mCurrentSlot < 0) {
1825 mCurrentSlot = 0;
1826 }
1827
1828 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1829#if DEBUG_POINTERS
1830 if (newSlot) {
1831 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001832 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001833 mCurrentSlot, mSlotCount - 1);
1834 }
1835#endif
1836 } else {
1837 Slot* slot = &mSlots[mCurrentSlot];
1838
1839 switch (rawEvent->code) {
1840 case ABS_MT_POSITION_X:
1841 slot->mInUse = true;
1842 slot->mAbsMTPositionX = rawEvent->value;
1843 break;
1844 case ABS_MT_POSITION_Y:
1845 slot->mInUse = true;
1846 slot->mAbsMTPositionY = rawEvent->value;
1847 break;
1848 case ABS_MT_TOUCH_MAJOR:
1849 slot->mInUse = true;
1850 slot->mAbsMTTouchMajor = rawEvent->value;
1851 break;
1852 case ABS_MT_TOUCH_MINOR:
1853 slot->mInUse = true;
1854 slot->mAbsMTTouchMinor = rawEvent->value;
1855 slot->mHaveAbsMTTouchMinor = true;
1856 break;
1857 case ABS_MT_WIDTH_MAJOR:
1858 slot->mInUse = true;
1859 slot->mAbsMTWidthMajor = rawEvent->value;
1860 break;
1861 case ABS_MT_WIDTH_MINOR:
1862 slot->mInUse = true;
1863 slot->mAbsMTWidthMinor = rawEvent->value;
1864 slot->mHaveAbsMTWidthMinor = true;
1865 break;
1866 case ABS_MT_ORIENTATION:
1867 slot->mInUse = true;
1868 slot->mAbsMTOrientation = rawEvent->value;
1869 break;
1870 case ABS_MT_TRACKING_ID:
1871 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1872 // The slot is no longer in use but it retains its previous contents,
1873 // which may be reused for subsequent touches.
1874 slot->mInUse = false;
1875 } else {
1876 slot->mInUse = true;
1877 slot->mAbsMTTrackingId = rawEvent->value;
1878 }
1879 break;
1880 case ABS_MT_PRESSURE:
1881 slot->mInUse = true;
1882 slot->mAbsMTPressure = rawEvent->value;
1883 break;
1884 case ABS_MT_DISTANCE:
1885 slot->mInUse = true;
1886 slot->mAbsMTDistance = rawEvent->value;
1887 break;
1888 case ABS_MT_TOOL_TYPE:
1889 slot->mInUse = true;
1890 slot->mAbsMTToolType = rawEvent->value;
1891 slot->mHaveAbsMTToolType = true;
1892 break;
1893 }
1894 }
1895 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1896 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1897 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001898 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1899 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901}
1902
1903void MultiTouchMotionAccumulator::finishSync() {
1904 if (!mUsingSlotsProtocol) {
1905 clearSlots(-1);
1906 }
1907}
1908
1909bool MultiTouchMotionAccumulator::hasStylus() const {
1910 return mHaveStylus;
1911}
1912
1913
1914// --- MultiTouchMotionAccumulator::Slot ---
1915
1916MultiTouchMotionAccumulator::Slot::Slot() {
1917 clear();
1918}
1919
1920void MultiTouchMotionAccumulator::Slot::clear() {
1921 mInUse = false;
1922 mHaveAbsMTTouchMinor = false;
1923 mHaveAbsMTWidthMinor = false;
1924 mHaveAbsMTToolType = false;
1925 mAbsMTPositionX = 0;
1926 mAbsMTPositionY = 0;
1927 mAbsMTTouchMajor = 0;
1928 mAbsMTTouchMinor = 0;
1929 mAbsMTWidthMajor = 0;
1930 mAbsMTWidthMinor = 0;
1931 mAbsMTOrientation = 0;
1932 mAbsMTTrackingId = -1;
1933 mAbsMTPressure = 0;
1934 mAbsMTDistance = 0;
1935 mAbsMTToolType = 0;
1936}
1937
1938int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1939 if (mHaveAbsMTToolType) {
1940 switch (mAbsMTToolType) {
1941 case MT_TOOL_FINGER:
1942 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1943 case MT_TOOL_PEN:
1944 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1945 }
1946 }
1947 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1948}
1949
1950
1951// --- InputMapper ---
1952
1953InputMapper::InputMapper(InputDevice* device) :
1954 mDevice(device), mContext(device->getContext()) {
1955}
1956
1957InputMapper::~InputMapper() {
1958}
1959
1960void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1961 info->addSource(getSources());
1962}
1963
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001964void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965}
1966
1967void InputMapper::configure(nsecs_t when,
1968 const InputReaderConfiguration* config, uint32_t changes) {
1969}
1970
1971void InputMapper::reset(nsecs_t when) {
1972}
1973
1974void InputMapper::timeoutExpired(nsecs_t when) {
1975}
1976
1977int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1978 return AKEY_STATE_UNKNOWN;
1979}
1980
1981int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1982 return AKEY_STATE_UNKNOWN;
1983}
1984
1985int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1986 return AKEY_STATE_UNKNOWN;
1987}
1988
1989bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1990 const int32_t* keyCodes, uint8_t* outFlags) {
1991 return false;
1992}
1993
1994void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1995 int32_t token) {
1996}
1997
1998void InputMapper::cancelVibrate(int32_t token) {
1999}
2000
Jeff Brownc9aa6282015-02-11 19:03:28 -08002001void InputMapper::cancelTouch(nsecs_t when) {
2002}
2003
Michael Wrightd02c5b62014-02-10 15:10:22 -08002004int32_t InputMapper::getMetaState() {
2005 return 0;
2006}
2007
Andrii Kulian763a3a42016-03-08 10:46:16 -08002008void InputMapper::updateMetaState(int32_t keyCode) {
2009}
2010
Michael Wright842500e2015-03-13 17:32:02 -07002011void InputMapper::updateExternalStylusState(const StylusState& state) {
2012
2013}
2014
Michael Wrightd02c5b62014-02-10 15:10:22 -08002015void InputMapper::fadePointer() {
2016}
2017
2018status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2019 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2020}
2021
2022void InputMapper::bumpGeneration() {
2023 mDevice->bumpGeneration();
2024}
2025
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002026void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002027 const RawAbsoluteAxisInfo& axis, const char* name) {
2028 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002029 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002030 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2031 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002032 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034}
2035
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002036void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2037 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2038 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2039 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2040 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002041}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042
2043// --- SwitchInputMapper ---
2044
2045SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002046 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047}
2048
2049SwitchInputMapper::~SwitchInputMapper() {
2050}
2051
2052uint32_t SwitchInputMapper::getSources() {
2053 return AINPUT_SOURCE_SWITCH;
2054}
2055
2056void SwitchInputMapper::process(const RawEvent* rawEvent) {
2057 switch (rawEvent->type) {
2058 case EV_SW:
2059 processSwitch(rawEvent->code, rawEvent->value);
2060 break;
2061
2062 case EV_SYN:
2063 if (rawEvent->code == SYN_REPORT) {
2064 sync(rawEvent->when);
2065 }
2066 }
2067}
2068
2069void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2070 if (switchCode >= 0 && switchCode < 32) {
2071 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002072 mSwitchValues |= 1 << switchCode;
2073 } else {
2074 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002075 }
2076 mUpdatedSwitchMask |= 1 << switchCode;
2077 }
2078}
2079
2080void SwitchInputMapper::sync(nsecs_t when) {
2081 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002082 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002083 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2084 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002085 getListener()->notifySwitch(&args);
2086
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 mUpdatedSwitchMask = 0;
2088 }
2089}
2090
2091int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2092 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2093}
2094
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002095void SwitchInputMapper::dump(std::string& dump) {
2096 dump += INDENT2 "Switch Input Mapper:\n";
2097 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002098}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099
2100// --- VibratorInputMapper ---
2101
2102VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2103 InputMapper(device), mVibrating(false) {
2104}
2105
2106VibratorInputMapper::~VibratorInputMapper() {
2107}
2108
2109uint32_t VibratorInputMapper::getSources() {
2110 return 0;
2111}
2112
2113void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2114 InputMapper::populateDeviceInfo(info);
2115
2116 info->setVibrator(true);
2117}
2118
2119void VibratorInputMapper::process(const RawEvent* rawEvent) {
2120 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2121}
2122
2123void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2124 int32_t token) {
2125#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002126 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002127 for (size_t i = 0; i < patternSize; i++) {
2128 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002129 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002130 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002131 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002132 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002133 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002134 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002135#endif
2136
2137 mVibrating = true;
2138 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2139 mPatternSize = patternSize;
2140 mRepeat = repeat;
2141 mToken = token;
2142 mIndex = -1;
2143
2144 nextStep();
2145}
2146
2147void VibratorInputMapper::cancelVibrate(int32_t token) {
2148#if DEBUG_VIBRATOR
2149 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2150#endif
2151
2152 if (mVibrating && mToken == token) {
2153 stopVibrating();
2154 }
2155}
2156
2157void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2158 if (mVibrating) {
2159 if (when >= mNextStepTime) {
2160 nextStep();
2161 } else {
2162 getContext()->requestTimeoutAtTime(mNextStepTime);
2163 }
2164 }
2165}
2166
2167void VibratorInputMapper::nextStep() {
2168 mIndex += 1;
2169 if (size_t(mIndex) >= mPatternSize) {
2170 if (mRepeat < 0) {
2171 // We are done.
2172 stopVibrating();
2173 return;
2174 }
2175 mIndex = mRepeat;
2176 }
2177
2178 bool vibratorOn = mIndex & 1;
2179 nsecs_t duration = mPattern[mIndex];
2180 if (vibratorOn) {
2181#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002182 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002183#endif
2184 getEventHub()->vibrate(getDeviceId(), duration);
2185 } else {
2186#if DEBUG_VIBRATOR
2187 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2188#endif
2189 getEventHub()->cancelVibrate(getDeviceId());
2190 }
2191 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2192 mNextStepTime = now + duration;
2193 getContext()->requestTimeoutAtTime(mNextStepTime);
2194#if DEBUG_VIBRATOR
2195 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2196#endif
2197}
2198
2199void VibratorInputMapper::stopVibrating() {
2200 mVibrating = false;
2201#if DEBUG_VIBRATOR
2202 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2203#endif
2204 getEventHub()->cancelVibrate(getDeviceId());
2205}
2206
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002207void VibratorInputMapper::dump(std::string& dump) {
2208 dump += INDENT2 "Vibrator Input Mapper:\n";
2209 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210}
2211
2212
2213// --- KeyboardInputMapper ---
2214
2215KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2216 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002217 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218}
2219
2220KeyboardInputMapper::~KeyboardInputMapper() {
2221}
2222
2223uint32_t KeyboardInputMapper::getSources() {
2224 return mSource;
2225}
2226
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002227int32_t KeyboardInputMapper::getOrientation() {
2228 if (mViewport) {
2229 return mViewport->orientation;
2230 }
2231 return DISPLAY_ORIENTATION_0;
2232}
2233
2234int32_t KeyboardInputMapper::getDisplayId() {
2235 if (mViewport) {
2236 return mViewport->displayId;
2237 }
2238 return ADISPLAY_ID_NONE;
2239}
2240
Michael Wrightd02c5b62014-02-10 15:10:22 -08002241void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2242 InputMapper::populateDeviceInfo(info);
2243
2244 info->setKeyboardType(mKeyboardType);
2245 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2246}
2247
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002248void KeyboardInputMapper::dump(std::string& dump) {
2249 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002251 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002252 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002253 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2254 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2255 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256}
2257
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258void KeyboardInputMapper::configure(nsecs_t when,
2259 const InputReaderConfiguration* config, uint32_t changes) {
2260 InputMapper::configure(when, config, changes);
2261
2262 if (!changes) { // first time only
2263 // Configure basic parameters.
2264 configureParameters();
2265 }
2266
2267 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002268 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002269 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 }
2271 }
2272}
2273
Ivan Podogovb9afef32017-02-13 15:34:32 +00002274static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2275 int32_t mapped = 0;
2276 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2277 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2278 if (stemKeyRotationMap[i][0] == keyCode) {
2279 stemKeyRotationMap[i][1] = mapped;
2280 return;
2281 }
2282 }
2283 }
2284}
2285
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286void KeyboardInputMapper::configureParameters() {
2287 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002288 const PropertyMap& config = getDevice()->getConfiguration();
2289 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002290 mParameters.orientationAware);
2291
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002293 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2294 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2295 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2296 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002297 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002298
2299 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002300 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002301 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002302}
2303
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002304void KeyboardInputMapper::dumpParameters(std::string& dump) {
2305 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002306 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002307 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002308 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002309 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310}
2311
2312void KeyboardInputMapper::reset(nsecs_t when) {
2313 mMetaState = AMETA_NONE;
2314 mDownTime = 0;
2315 mKeyDowns.clear();
2316 mCurrentHidUsage = 0;
2317
2318 resetLedState();
2319
2320 InputMapper::reset(when);
2321}
2322
2323void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2324 switch (rawEvent->type) {
2325 case EV_KEY: {
2326 int32_t scanCode = rawEvent->code;
2327 int32_t usageCode = mCurrentHidUsage;
2328 mCurrentHidUsage = 0;
2329
2330 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002331 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002332 }
2333 break;
2334 }
2335 case EV_MSC: {
2336 if (rawEvent->code == MSC_SCAN) {
2337 mCurrentHidUsage = rawEvent->value;
2338 }
2339 break;
2340 }
2341 case EV_SYN: {
2342 if (rawEvent->code == SYN_REPORT) {
2343 mCurrentHidUsage = 0;
2344 }
2345 }
2346 }
2347}
2348
2349bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2350 return scanCode < BTN_MOUSE
2351 || scanCode >= KEY_OK
2352 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2353 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2354}
2355
Michael Wright58ba9882017-07-26 16:19:11 +01002356bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2357 switch (keyCode) {
2358 case AKEYCODE_MEDIA_PLAY:
2359 case AKEYCODE_MEDIA_PAUSE:
2360 case AKEYCODE_MEDIA_PLAY_PAUSE:
2361 case AKEYCODE_MUTE:
2362 case AKEYCODE_HEADSETHOOK:
2363 case AKEYCODE_MEDIA_STOP:
2364 case AKEYCODE_MEDIA_NEXT:
2365 case AKEYCODE_MEDIA_PREVIOUS:
2366 case AKEYCODE_MEDIA_REWIND:
2367 case AKEYCODE_MEDIA_RECORD:
2368 case AKEYCODE_MEDIA_FAST_FORWARD:
2369 case AKEYCODE_MEDIA_SKIP_FORWARD:
2370 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2371 case AKEYCODE_MEDIA_STEP_FORWARD:
2372 case AKEYCODE_MEDIA_STEP_BACKWARD:
2373 case AKEYCODE_MEDIA_AUDIO_TRACK:
2374 case AKEYCODE_VOLUME_UP:
2375 case AKEYCODE_VOLUME_DOWN:
2376 case AKEYCODE_VOLUME_MUTE:
2377 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2378 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2379 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2380 return true;
2381 }
2382 return false;
2383}
2384
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002385void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2386 int32_t usageCode) {
2387 int32_t keyCode;
2388 int32_t keyMetaState;
2389 uint32_t policyFlags;
2390
2391 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2392 &keyCode, &keyMetaState, &policyFlags)) {
2393 keyCode = AKEYCODE_UNKNOWN;
2394 keyMetaState = mMetaState;
2395 policyFlags = 0;
2396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397
2398 if (down) {
2399 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002400 if (mParameters.orientationAware) {
2401 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
2403
2404 // Add key down.
2405 ssize_t keyDownIndex = findKeyDown(scanCode);
2406 if (keyDownIndex >= 0) {
2407 // key repeat, be sure to use same keycode as before in case of rotation
2408 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2409 } else {
2410 // key down
2411 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2412 && mContext->shouldDropVirtualKey(when,
2413 getDevice(), keyCode, scanCode)) {
2414 return;
2415 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002416 if (policyFlags & POLICY_FLAG_GESTURE) {
2417 mDevice->cancelTouch(when);
2418 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002419
2420 mKeyDowns.push();
2421 KeyDown& keyDown = mKeyDowns.editTop();
2422 keyDown.keyCode = keyCode;
2423 keyDown.scanCode = scanCode;
2424 }
2425
2426 mDownTime = when;
2427 } else {
2428 // Remove key down.
2429 ssize_t keyDownIndex = findKeyDown(scanCode);
2430 if (keyDownIndex >= 0) {
2431 // key up, be sure to use same keycode as before in case of rotation
2432 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2433 mKeyDowns.removeAt(size_t(keyDownIndex));
2434 } else {
2435 // key was not actually down
2436 ALOGI("Dropping key up from device %s because the key was not down. "
2437 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002438 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002439 return;
2440 }
2441 }
2442
Andrii Kulian763a3a42016-03-08 10:46:16 -08002443 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002444 // If global meta state changed send it along with the key.
2445 // If it has not changed then we'll use what keymap gave us,
2446 // since key replacement logic might temporarily reset a few
2447 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002448 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002449 }
2450
2451 nsecs_t downTime = mDownTime;
2452
2453 // Key down on external an keyboard should wake the device.
2454 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2455 // For internal keyboards, the key layout file should specify the policy flags for
2456 // each wake key individually.
2457 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002458 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002459 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002460 }
2461
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002462 if (mParameters.handlesKeyRepeat) {
2463 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2464 }
2465
Prabir Pradhan42611e02018-11-27 14:04:02 -08002466 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2467 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002468 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002469 getListener()->notifyKey(&args);
2470}
2471
2472ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2473 size_t n = mKeyDowns.size();
2474 for (size_t i = 0; i < n; i++) {
2475 if (mKeyDowns[i].scanCode == scanCode) {
2476 return i;
2477 }
2478 }
2479 return -1;
2480}
2481
2482int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2483 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2484}
2485
2486int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2487 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2488}
2489
2490bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2491 const int32_t* keyCodes, uint8_t* outFlags) {
2492 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2493}
2494
2495int32_t KeyboardInputMapper::getMetaState() {
2496 return mMetaState;
2497}
2498
Andrii Kulian763a3a42016-03-08 10:46:16 -08002499void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2500 updateMetaStateIfNeeded(keyCode, false);
2501}
2502
2503bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2504 int32_t oldMetaState = mMetaState;
2505 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2506 bool metaStateChanged = oldMetaState != newMetaState;
2507 if (metaStateChanged) {
2508 mMetaState = newMetaState;
2509 updateLedState(false);
2510
2511 getContext()->updateGlobalMetaState();
2512 }
2513
2514 return metaStateChanged;
2515}
2516
Michael Wrightd02c5b62014-02-10 15:10:22 -08002517void KeyboardInputMapper::resetLedState() {
2518 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2519 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2520 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2521
2522 updateLedState(true);
2523}
2524
2525void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2526 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2527 ledState.on = false;
2528}
2529
2530void KeyboardInputMapper::updateLedState(bool reset) {
2531 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2532 AMETA_CAPS_LOCK_ON, reset);
2533 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2534 AMETA_NUM_LOCK_ON, reset);
2535 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2536 AMETA_SCROLL_LOCK_ON, reset);
2537}
2538
2539void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2540 int32_t led, int32_t modifier, bool reset) {
2541 if (ledState.avail) {
2542 bool desiredState = (mMetaState & modifier) != 0;
2543 if (reset || ledState.on != desiredState) {
2544 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2545 ledState.on = desiredState;
2546 }
2547 }
2548}
2549
2550
2551// --- CursorInputMapper ---
2552
2553CursorInputMapper::CursorInputMapper(InputDevice* device) :
2554 InputMapper(device) {
2555}
2556
2557CursorInputMapper::~CursorInputMapper() {
2558}
2559
2560uint32_t CursorInputMapper::getSources() {
2561 return mSource;
2562}
2563
2564void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2565 InputMapper::populateDeviceInfo(info);
2566
2567 if (mParameters.mode == Parameters::MODE_POINTER) {
2568 float minX, minY, maxX, maxY;
2569 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2570 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2571 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2572 }
2573 } else {
2574 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2575 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2576 }
2577 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2578
2579 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2580 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2581 }
2582 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2583 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2584 }
2585}
2586
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002587void CursorInputMapper::dump(std::string& dump) {
2588 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002589 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002590 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2591 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2592 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2593 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2594 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002595 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002596 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002597 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002598 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2599 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2600 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2601 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2602 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2603 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002604}
2605
2606void CursorInputMapper::configure(nsecs_t when,
2607 const InputReaderConfiguration* config, uint32_t changes) {
2608 InputMapper::configure(when, config, changes);
2609
2610 if (!changes) { // first time only
2611 mCursorScrollAccumulator.configure(getDevice());
2612
2613 // Configure basic parameters.
2614 configureParameters();
2615
2616 // Configure device mode.
2617 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002618 case Parameters::MODE_POINTER_RELATIVE:
2619 // Should not happen during first time configuration.
2620 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2621 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002622 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002623 case Parameters::MODE_POINTER:
2624 mSource = AINPUT_SOURCE_MOUSE;
2625 mXPrecision = 1.0f;
2626 mYPrecision = 1.0f;
2627 mXScale = 1.0f;
2628 mYScale = 1.0f;
2629 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2630 break;
2631 case Parameters::MODE_NAVIGATION:
2632 mSource = AINPUT_SOURCE_TRACKBALL;
2633 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2634 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2635 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2636 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2637 break;
2638 }
2639
2640 mVWheelScale = 1.0f;
2641 mHWheelScale = 1.0f;
2642 }
2643
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002644 if ((!changes && config->pointerCapture)
2645 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2646 if (config->pointerCapture) {
2647 if (mParameters.mode == Parameters::MODE_POINTER) {
2648 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2649 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2650 // Keep PointerController around in order to preserve the pointer position.
2651 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2652 } else {
2653 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2654 }
2655 } else {
2656 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2657 mParameters.mode = Parameters::MODE_POINTER;
2658 mSource = AINPUT_SOURCE_MOUSE;
2659 } else {
2660 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2661 }
2662 }
2663 bumpGeneration();
2664 if (changes) {
2665 getDevice()->notifyReset(when);
2666 }
2667 }
2668
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2670 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2671 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2672 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2673 }
2674
2675 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002676 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002678 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002679 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002680 if (internalViewport) {
2681 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002684
2685 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002686 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002687 getPolicy()->obtainPointerController(getDeviceId());
2688 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 bumpGeneration();
2690 }
2691}
2692
2693void CursorInputMapper::configureParameters() {
2694 mParameters.mode = Parameters::MODE_POINTER;
2695 String8 cursorModeString;
2696 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2697 if (cursorModeString == "navigation") {
2698 mParameters.mode = Parameters::MODE_NAVIGATION;
2699 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2700 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2701 }
2702 }
2703
2704 mParameters.orientationAware = false;
2705 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2706 mParameters.orientationAware);
2707
2708 mParameters.hasAssociatedDisplay = false;
2709 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2710 mParameters.hasAssociatedDisplay = true;
2711 }
2712}
2713
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002714void CursorInputMapper::dumpParameters(std::string& dump) {
2715 dump += INDENT3 "Parameters:\n";
2716 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002717 toString(mParameters.hasAssociatedDisplay));
2718
2719 switch (mParameters.mode) {
2720 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002721 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002723 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002724 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002725 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002726 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002727 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002728 break;
2729 default:
2730 ALOG_ASSERT(false);
2731 }
2732
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002733 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734 toString(mParameters.orientationAware));
2735}
2736
2737void CursorInputMapper::reset(nsecs_t when) {
2738 mButtonState = 0;
2739 mDownTime = 0;
2740
2741 mPointerVelocityControl.reset();
2742 mWheelXVelocityControl.reset();
2743 mWheelYVelocityControl.reset();
2744
2745 mCursorButtonAccumulator.reset(getDevice());
2746 mCursorMotionAccumulator.reset(getDevice());
2747 mCursorScrollAccumulator.reset(getDevice());
2748
2749 InputMapper::reset(when);
2750}
2751
2752void CursorInputMapper::process(const RawEvent* rawEvent) {
2753 mCursorButtonAccumulator.process(rawEvent);
2754 mCursorMotionAccumulator.process(rawEvent);
2755 mCursorScrollAccumulator.process(rawEvent);
2756
2757 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2758 sync(rawEvent->when);
2759 }
2760}
2761
2762void CursorInputMapper::sync(nsecs_t when) {
2763 int32_t lastButtonState = mButtonState;
2764 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2765 mButtonState = currentButtonState;
2766
2767 bool wasDown = isPointerDown(lastButtonState);
2768 bool down = isPointerDown(currentButtonState);
2769 bool downChanged;
2770 if (!wasDown && down) {
2771 mDownTime = when;
2772 downChanged = true;
2773 } else if (wasDown && !down) {
2774 downChanged = true;
2775 } else {
2776 downChanged = false;
2777 }
2778 nsecs_t downTime = mDownTime;
2779 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002780 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2781 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782
2783 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2784 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2785 bool moved = deltaX != 0 || deltaY != 0;
2786
2787 // Rotate delta according to orientation if needed.
2788 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2789 && (deltaX != 0.0f || deltaY != 0.0f)) {
2790 rotateDelta(mOrientation, &deltaX, &deltaY);
2791 }
2792
2793 // Move the pointer.
2794 PointerProperties pointerProperties;
2795 pointerProperties.clear();
2796 pointerProperties.id = 0;
2797 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2798
2799 PointerCoords pointerCoords;
2800 pointerCoords.clear();
2801
2802 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2803 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2804 bool scrolled = vscroll != 0 || hscroll != 0;
2805
Yi Kong9b14ac62018-07-17 13:48:38 -07002806 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2807 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002808
2809 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2810
2811 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002812 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002813 if (moved || scrolled || buttonsChanged) {
2814 mPointerController->setPresentation(
2815 PointerControllerInterface::PRESENTATION_POINTER);
2816
2817 if (moved) {
2818 mPointerController->move(deltaX, deltaY);
2819 }
2820
2821 if (buttonsChanged) {
2822 mPointerController->setButtonState(currentButtonState);
2823 }
2824
2825 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2826 }
2827
2828 float x, y;
2829 mPointerController->getPosition(&x, &y);
2830 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2831 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002832 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2833 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002834 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002835 } else {
2836 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2837 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2838 displayId = ADISPLAY_ID_NONE;
2839 }
2840
2841 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2842
2843 // Moving an external trackball or mouse should wake the device.
2844 // We don't do this for internal cursor devices to prevent them from waking up
2845 // the device in your pocket.
2846 // TODO: Use the input device configuration to control this behavior more finely.
2847 uint32_t policyFlags = 0;
2848 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002849 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 }
2851
2852 // Synthesize key down from buttons if needed.
2853 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002854 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002855
2856 // Send motion event.
2857 if (downChanged || moved || scrolled || buttonsChanged) {
2858 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002859 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002860 int32_t motionEventAction;
2861 if (downChanged) {
2862 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002863 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2865 } else {
2866 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2867 }
2868
Michael Wright7b159c92015-05-14 14:48:03 +01002869 if (buttonsReleased) {
2870 BitSet32 released(buttonsReleased);
2871 while (!released.isEmpty()) {
2872 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2873 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002874 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2875 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002876 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002877 metaState, buttonState,
2878 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002879 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002880 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002881 getListener()->notifyMotion(&releaseArgs);
2882 }
2883 }
2884
Prabir Pradhan42611e02018-11-27 14:04:02 -08002885 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2886 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002887 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002888 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002889 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002890 getListener()->notifyMotion(&args);
2891
Michael Wright7b159c92015-05-14 14:48:03 +01002892 if (buttonsPressed) {
2893 BitSet32 pressed(buttonsPressed);
2894 while (!pressed.isEmpty()) {
2895 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2896 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002897 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2898 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002899 actionButton, 0, metaState, buttonState,
2900 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002901 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002902 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002903 getListener()->notifyMotion(&pressArgs);
2904 }
2905 }
2906
2907 ALOG_ASSERT(buttonState == currentButtonState);
2908
Michael Wrightd02c5b62014-02-10 15:10:22 -08002909 // Send hover move after UP to tell the application that the mouse is hovering now.
2910 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002911 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002912 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2913 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002914 metaState, currentButtonState,
2915 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002916 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002917 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 getListener()->notifyMotion(&hoverArgs);
2919 }
2920
2921 // Send scroll events.
2922 if (scrolled) {
2923 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2924 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2925
Prabir Pradhan42611e02018-11-27 14:04:02 -08002926 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2927 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002928 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002929 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002930 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002931 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002932 getListener()->notifyMotion(&scrollArgs);
2933 }
2934 }
2935
2936 // Synthesize key up from buttons if needed.
2937 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002938 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002939
2940 mCursorMotionAccumulator.finishSync();
2941 mCursorScrollAccumulator.finishSync();
2942}
2943
2944int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2945 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2946 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2947 } else {
2948 return AKEY_STATE_UNKNOWN;
2949 }
2950}
2951
2952void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002953 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002954 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2955 }
2956}
2957
Arthur Hungc23540e2018-11-29 20:42:11 +08002958std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2959 if (mParameters.hasAssociatedDisplay) {
2960 if (mParameters.mode == Parameters::MODE_POINTER) {
2961 return std::make_optional(mPointerController->getDisplayId());
2962 } else {
2963 // If the device is orientationAware and not a mouse,
2964 // it expects to dispatch events to any display
2965 return std::make_optional(ADISPLAY_ID_NONE);
2966 }
2967 }
2968 return std::nullopt;
2969}
2970
Prashant Malani1941ff52015-08-11 18:29:28 -07002971// --- RotaryEncoderInputMapper ---
2972
2973RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002974 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002975 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2976}
2977
2978RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2979}
2980
2981uint32_t RotaryEncoderInputMapper::getSources() {
2982 return mSource;
2983}
2984
2985void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2986 InputMapper::populateDeviceInfo(info);
2987
2988 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002989 float res = 0.0f;
2990 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2991 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2992 }
2993 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2994 mScalingFactor)) {
2995 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2996 "default to 1.0!\n");
2997 mScalingFactor = 1.0f;
2998 }
2999 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3000 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003001 }
3002}
3003
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003004void RotaryEncoderInputMapper::dump(std::string& dump) {
3005 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
3006 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07003007 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
3008}
3009
3010void RotaryEncoderInputMapper::configure(nsecs_t when,
3011 const InputReaderConfiguration* config, uint32_t changes) {
3012 InputMapper::configure(when, config, changes);
3013 if (!changes) {
3014 mRotaryEncoderScrollAccumulator.configure(getDevice());
3015 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003016 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003017 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003018 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003019 if (internalViewport) {
3020 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003021 } else {
3022 mOrientation = DISPLAY_ORIENTATION_0;
3023 }
3024 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003025}
3026
3027void RotaryEncoderInputMapper::reset(nsecs_t when) {
3028 mRotaryEncoderScrollAccumulator.reset(getDevice());
3029
3030 InputMapper::reset(when);
3031}
3032
3033void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3034 mRotaryEncoderScrollAccumulator.process(rawEvent);
3035
3036 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3037 sync(rawEvent->when);
3038 }
3039}
3040
3041void RotaryEncoderInputMapper::sync(nsecs_t when) {
3042 PointerCoords pointerCoords;
3043 pointerCoords.clear();
3044
3045 PointerProperties pointerProperties;
3046 pointerProperties.clear();
3047 pointerProperties.id = 0;
3048 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3049
3050 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3051 bool scrolled = scroll != 0;
3052
3053 // This is not a pointer, so it's not associated with a display.
3054 int32_t displayId = ADISPLAY_ID_NONE;
3055
3056 // Moving the rotary encoder should wake the device (if specified).
3057 uint32_t policyFlags = 0;
3058 if (scrolled && getDevice()->isExternal()) {
3059 policyFlags |= POLICY_FLAG_WAKE;
3060 }
3061
Ivan Podogovad437252016-09-29 16:29:55 +01003062 if (mOrientation == DISPLAY_ORIENTATION_180) {
3063 scroll = -scroll;
3064 }
3065
Prashant Malani1941ff52015-08-11 18:29:28 -07003066 // Send motion event.
3067 if (scrolled) {
3068 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003069 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003070
Prabir Pradhan42611e02018-11-27 14:04:02 -08003071 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3072 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08003073 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0,
3074 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003075 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003076 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003077 getListener()->notifyMotion(&scrollArgs);
3078 }
3079
3080 mRotaryEncoderScrollAccumulator.finishSync();
3081}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003082
3083// --- TouchInputMapper ---
3084
3085TouchInputMapper::TouchInputMapper(InputDevice* device) :
3086 InputMapper(device),
3087 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3088 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003089 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3091}
3092
3093TouchInputMapper::~TouchInputMapper() {
3094}
3095
3096uint32_t TouchInputMapper::getSources() {
3097 return mSource;
3098}
3099
3100void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3101 InputMapper::populateDeviceInfo(info);
3102
3103 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3104 info->addMotionRange(mOrientedRanges.x);
3105 info->addMotionRange(mOrientedRanges.y);
3106 info->addMotionRange(mOrientedRanges.pressure);
3107
3108 if (mOrientedRanges.haveSize) {
3109 info->addMotionRange(mOrientedRanges.size);
3110 }
3111
3112 if (mOrientedRanges.haveTouchSize) {
3113 info->addMotionRange(mOrientedRanges.touchMajor);
3114 info->addMotionRange(mOrientedRanges.touchMinor);
3115 }
3116
3117 if (mOrientedRanges.haveToolSize) {
3118 info->addMotionRange(mOrientedRanges.toolMajor);
3119 info->addMotionRange(mOrientedRanges.toolMinor);
3120 }
3121
3122 if (mOrientedRanges.haveOrientation) {
3123 info->addMotionRange(mOrientedRanges.orientation);
3124 }
3125
3126 if (mOrientedRanges.haveDistance) {
3127 info->addMotionRange(mOrientedRanges.distance);
3128 }
3129
3130 if (mOrientedRanges.haveTilt) {
3131 info->addMotionRange(mOrientedRanges.tilt);
3132 }
3133
3134 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3135 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3136 0.0f);
3137 }
3138 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3139 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3140 0.0f);
3141 }
3142 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3143 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3144 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3145 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3146 x.fuzz, x.resolution);
3147 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3148 y.fuzz, y.resolution);
3149 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3150 x.fuzz, x.resolution);
3151 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3152 y.fuzz, y.resolution);
3153 }
3154 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3155 }
3156}
3157
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003158void TouchInputMapper::dump(std::string& dump) {
3159 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 dumpParameters(dump);
3161 dumpVirtualKeys(dump);
3162 dumpRawPointerAxes(dump);
3163 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003164 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003165 dumpSurface(dump);
3166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003167 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3168 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3169 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3170 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3171 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3172 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3173 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3174 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3175 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3176 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3177 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3178 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3179 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3180 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3181 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3182 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3183 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003185 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3186 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003187 mLastRawState.rawPointerData.pointerCount);
3188 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3189 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003190 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003191 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3192 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3193 "toolType=%d, isHovering=%s\n", i,
3194 pointer.id, pointer.x, pointer.y, pointer.pressure,
3195 pointer.touchMajor, pointer.touchMinor,
3196 pointer.toolMajor, pointer.toolMinor,
3197 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3198 pointer.toolType, toString(pointer.isHovering));
3199 }
3200
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003201 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3202 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003203 mLastCookedState.cookedPointerData.pointerCount);
3204 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3205 const PointerProperties& pointerProperties =
3206 mLastCookedState.cookedPointerData.pointerProperties[i];
3207 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003208 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3210 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3211 "toolType=%d, isHovering=%s\n", i,
3212 pointerProperties.id,
3213 pointerCoords.getX(),
3214 pointerCoords.getY(),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3217 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3218 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3219 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3220 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3221 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3222 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3223 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003224 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 }
3226
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003227 dump += INDENT3 "Stylus Fusion:\n";
3228 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003229 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3231 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003232 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003233 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003234 dumpStylusState(dump, mExternalStylusState);
3235
Michael Wrightd02c5b62014-02-10 15:10:22 -08003236 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003237 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3238 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003240 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003242 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003243 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003244 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003246 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 mPointerGestureMaxSwipeWidth);
3248 }
3249}
3250
Santos Cordonfa5cf462017-04-05 10:37:00 -07003251const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3252 switch (deviceMode) {
3253 case DEVICE_MODE_DISABLED:
3254 return "disabled";
3255 case DEVICE_MODE_DIRECT:
3256 return "direct";
3257 case DEVICE_MODE_UNSCALED:
3258 return "unscaled";
3259 case DEVICE_MODE_NAVIGATION:
3260 return "navigation";
3261 case DEVICE_MODE_POINTER:
3262 return "pointer";
3263 }
3264 return "unknown";
3265}
3266
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267void TouchInputMapper::configure(nsecs_t when,
3268 const InputReaderConfiguration* config, uint32_t changes) {
3269 InputMapper::configure(when, config, changes);
3270
3271 mConfig = *config;
3272
3273 if (!changes) { // first time only
3274 // Configure basic parameters.
3275 configureParameters();
3276
3277 // Configure common accumulators.
3278 mCursorScrollAccumulator.configure(getDevice());
3279 mTouchButtonAccumulator.configure(getDevice());
3280
3281 // Configure absolute axis information.
3282 configureRawPointerAxes();
3283
3284 // Prepare input device calibration.
3285 parseCalibration();
3286 resolveCalibration();
3287 }
3288
Michael Wright842500e2015-03-13 17:32:02 -07003289 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003290 // Update location calibration to reflect current settings
3291 updateAffineTransformation();
3292 }
3293
Michael Wrightd02c5b62014-02-10 15:10:22 -08003294 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3295 // Update pointer speed.
3296 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3297 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3298 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3299 }
3300
3301 bool resetNeeded = false;
3302 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3303 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003304 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3305 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003306 // Configure device sources, surface dimensions, orientation and
3307 // scaling factors.
3308 configureSurface(when, &resetNeeded);
3309 }
3310
3311 if (changes && resetNeeded) {
3312 // Send reset, unless this is the first time the device has been configured,
3313 // in which case the reader will call reset itself after all mappers are ready.
3314 getDevice()->notifyReset(when);
3315 }
3316}
3317
Michael Wright842500e2015-03-13 17:32:02 -07003318void TouchInputMapper::resolveExternalStylusPresence() {
3319 Vector<InputDeviceInfo> devices;
3320 mContext->getExternalStylusDevices(devices);
3321 mExternalStylusConnected = !devices.isEmpty();
3322
3323 if (!mExternalStylusConnected) {
3324 resetExternalStylus();
3325 }
3326}
3327
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328void TouchInputMapper::configureParameters() {
3329 // Use the pointer presentation mode for devices that do not support distinct
3330 // multitouch. The spot-based presentation relies on being able to accurately
3331 // locate two or more fingers on the touch pad.
3332 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003333 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334
3335 String8 gestureModeString;
3336 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3337 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003338 if (gestureModeString == "single-touch") {
3339 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3340 } else if (gestureModeString == "multi-touch") {
3341 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 } else if (gestureModeString != "default") {
3343 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3344 }
3345 }
3346
3347 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3348 // The device is a touch screen.
3349 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3350 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3351 // The device is a pointing device like a track pad.
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3353 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3354 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3355 // The device is a cursor device with a touch pad attached.
3356 // By default don't use the touch pad to move the pointer.
3357 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3358 } else {
3359 // The device is a touch pad of unknown purpose.
3360 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3361 }
3362
3363 mParameters.hasButtonUnderPad=
3364 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3365
3366 String8 deviceTypeString;
3367 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3368 deviceTypeString)) {
3369 if (deviceTypeString == "touchScreen") {
3370 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3371 } else if (deviceTypeString == "touchPad") {
3372 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3373 } else if (deviceTypeString == "touchNavigation") {
3374 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3375 } else if (deviceTypeString == "pointer") {
3376 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3377 } else if (deviceTypeString != "default") {
3378 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3379 }
3380 }
3381
3382 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3383 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3384 mParameters.orientationAware);
3385
3386 mParameters.hasAssociatedDisplay = false;
3387 mParameters.associatedDisplayIsExternal = false;
3388 if (mParameters.orientationAware
3389 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3390 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3391 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003392 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3393 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003394 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003395 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003396 uniqueDisplayId);
3397 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003398 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003400 if (getDevice()->getAssociatedDisplayPort()) {
3401 mParameters.hasAssociatedDisplay = true;
3402 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003403
3404 // Initial downs on external touch devices should wake the device.
3405 // Normally we don't do this for internal touch screens to prevent them from waking
3406 // up in your pocket but you can enable it using the input device configuration.
3407 mParameters.wake = getDevice()->isExternal();
3408 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3409 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410}
3411
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003412void TouchInputMapper::dumpParameters(std::string& dump) {
3413 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003414
3415 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003416 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003417 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003418 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003419 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003420 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003421 break;
3422 default:
3423 assert(false);
3424 }
3425
3426 switch (mParameters.deviceType) {
3427 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003428 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 break;
3430 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003431 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 break;
3433 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003434 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003435 break;
3436 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003437 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003438 break;
3439 default:
3440 ALOG_ASSERT(false);
3441 }
3442
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003443 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003444 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003445 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003446 toString(mParameters.associatedDisplayIsExternal),
3447 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003448 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003449 toString(mParameters.orientationAware));
3450}
3451
3452void TouchInputMapper::configureRawPointerAxes() {
3453 mRawPointerAxes.clear();
3454}
3455
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003456void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3457 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3461 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3462 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3463 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3464 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3465 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3466 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3467 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3468 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3469 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3470 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3471}
3472
Michael Wright842500e2015-03-13 17:32:02 -07003473bool TouchInputMapper::hasExternalStylus() const {
3474 return mExternalStylusConnected;
3475}
3476
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003477/**
3478 * Determine which DisplayViewport to use.
3479 * 1. If display port is specified, return the matching viewport. If matching viewport not
3480 * found, then return.
3481 * 2. If a device has associated display, get the matching viewport by either unique id or by
3482 * the display type (internal or external).
3483 * 3. Otherwise, use a non-display viewport.
3484 */
3485std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3486 if (mParameters.hasAssociatedDisplay) {
3487 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3488 if (displayPort) {
3489 // Find the viewport that contains the same port
3490 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3491 if (!v) {
3492 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3493 "but the corresponding viewport is not found.",
3494 getDeviceName().c_str(), *displayPort);
3495 }
3496 return v;
3497 }
3498
3499 if (!mParameters.uniqueDisplayId.empty()) {
3500 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3501 }
3502
3503 ViewportType viewportTypeToUse;
3504 if (mParameters.associatedDisplayIsExternal) {
3505 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3506 } else {
3507 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3508 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003509
3510 std::optional<DisplayViewport> viewport =
3511 mConfig.getDisplayViewportByType(viewportTypeToUse);
3512 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3513 ALOGW("Input device %s should be associated with external display, "
3514 "fallback to internal one for the external viewport is not found.",
3515 getDeviceName().c_str());
3516 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3517 }
3518
3519 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003520 }
3521
3522 DisplayViewport newViewport;
3523 // Raw width and height in the natural orientation.
3524 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3525 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3526 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3527 return std::make_optional(newViewport);
3528}
3529
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3531 int32_t oldDeviceMode = mDeviceMode;
3532
Michael Wright842500e2015-03-13 17:32:02 -07003533 resolveExternalStylusPresence();
3534
Michael Wrightd02c5b62014-02-10 15:10:22 -08003535 // Determine device mode.
3536 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3537 && mConfig.pointerGesturesEnabled) {
3538 mSource = AINPUT_SOURCE_MOUSE;
3539 mDeviceMode = DEVICE_MODE_POINTER;
3540 if (hasStylus()) {
3541 mSource |= AINPUT_SOURCE_STYLUS;
3542 }
3543 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3544 && mParameters.hasAssociatedDisplay) {
3545 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3546 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003547 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003548 mSource |= AINPUT_SOURCE_STYLUS;
3549 }
Michael Wright2f78b682015-06-12 15:25:08 +01003550 if (hasExternalStylus()) {
3551 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3552 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003553 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3554 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3555 mDeviceMode = DEVICE_MODE_NAVIGATION;
3556 } else {
3557 mSource = AINPUT_SOURCE_TOUCHPAD;
3558 mDeviceMode = DEVICE_MODE_UNSCALED;
3559 }
3560
3561 // Ensure we have valid X and Y axes.
3562 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003563 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003564 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003565 mDeviceMode = DEVICE_MODE_DISABLED;
3566 return;
3567 }
3568
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003569 // Get associated display dimensions.
3570 std::optional<DisplayViewport> newViewport = findViewport();
3571 if (!newViewport) {
3572 ALOGI("Touch device '%s' could not query the properties of its associated "
3573 "display. The device will be inoperable until the display size "
3574 "becomes available.",
3575 getDeviceName().c_str());
3576 mDeviceMode = DEVICE_MODE_DISABLED;
3577 return;
3578 }
3579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003581 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3582 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003583
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003584 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003586 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003587
3588 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3589 // Convert rotated viewport to natural surface coordinates.
3590 int32_t naturalLogicalWidth, naturalLogicalHeight;
3591 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3592 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3593 int32_t naturalDeviceWidth, naturalDeviceHeight;
3594 switch (mViewport.orientation) {
3595 case DISPLAY_ORIENTATION_90:
3596 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3597 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3598 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3599 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3600 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3601 naturalPhysicalTop = mViewport.physicalLeft;
3602 naturalDeviceWidth = mViewport.deviceHeight;
3603 naturalDeviceHeight = mViewport.deviceWidth;
3604 break;
3605 case DISPLAY_ORIENTATION_180:
3606 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3607 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3608 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3609 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3610 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3611 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3612 naturalDeviceWidth = mViewport.deviceWidth;
3613 naturalDeviceHeight = mViewport.deviceHeight;
3614 break;
3615 case DISPLAY_ORIENTATION_270:
3616 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3617 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3618 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3619 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3620 naturalPhysicalLeft = mViewport.physicalTop;
3621 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3622 naturalDeviceWidth = mViewport.deviceHeight;
3623 naturalDeviceHeight = mViewport.deviceWidth;
3624 break;
3625 case DISPLAY_ORIENTATION_0:
3626 default:
3627 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3628 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3629 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3630 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3631 naturalPhysicalLeft = mViewport.physicalLeft;
3632 naturalPhysicalTop = mViewport.physicalTop;
3633 naturalDeviceWidth = mViewport.deviceWidth;
3634 naturalDeviceHeight = mViewport.deviceHeight;
3635 break;
3636 }
3637
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003638 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3639 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3640 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3641 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3642 }
3643
Michael Wright358bcc72018-08-21 04:01:07 +01003644 mPhysicalWidth = naturalPhysicalWidth;
3645 mPhysicalHeight = naturalPhysicalHeight;
3646 mPhysicalLeft = naturalPhysicalLeft;
3647 mPhysicalTop = naturalPhysicalTop;
3648
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3650 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3651 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3652 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3653
3654 mSurfaceOrientation = mParameters.orientationAware ?
3655 mViewport.orientation : DISPLAY_ORIENTATION_0;
3656 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003657 mPhysicalWidth = rawWidth;
3658 mPhysicalHeight = rawHeight;
3659 mPhysicalLeft = 0;
3660 mPhysicalTop = 0;
3661
Michael Wrightd02c5b62014-02-10 15:10:22 -08003662 mSurfaceWidth = rawWidth;
3663 mSurfaceHeight = rawHeight;
3664 mSurfaceLeft = 0;
3665 mSurfaceTop = 0;
3666 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3667 }
3668 }
3669
3670 // If moving between pointer modes, need to reset some state.
3671 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3672 if (deviceModeChanged) {
3673 mOrientedRanges.clear();
3674 }
3675
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003676 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003677 if (mDeviceMode == DEVICE_MODE_POINTER ||
3678 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003679 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003680 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3681 }
3682 } else {
3683 mPointerController.clear();
3684 }
3685
3686 if (viewportChanged || deviceModeChanged) {
3687 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3688 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003689 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3691
3692 // Configure X and Y factors.
3693 mXScale = float(mSurfaceWidth) / rawWidth;
3694 mYScale = float(mSurfaceHeight) / rawHeight;
3695 mXTranslate = -mSurfaceLeft;
3696 mYTranslate = -mSurfaceTop;
3697 mXPrecision = 1.0f / mXScale;
3698 mYPrecision = 1.0f / mYScale;
3699
3700 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3701 mOrientedRanges.x.source = mSource;
3702 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3703 mOrientedRanges.y.source = mSource;
3704
3705 configureVirtualKeys();
3706
3707 // Scale factor for terms that are not oriented in a particular axis.
3708 // If the pixels are square then xScale == yScale otherwise we fake it
3709 // by choosing an average.
3710 mGeometricScale = avg(mXScale, mYScale);
3711
3712 // Size of diagonal axis.
3713 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3714
3715 // Size factors.
3716 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3717 if (mRawPointerAxes.touchMajor.valid
3718 && mRawPointerAxes.touchMajor.maxValue != 0) {
3719 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3720 } else if (mRawPointerAxes.toolMajor.valid
3721 && mRawPointerAxes.toolMajor.maxValue != 0) {
3722 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3723 } else {
3724 mSizeScale = 0.0f;
3725 }
3726
3727 mOrientedRanges.haveTouchSize = true;
3728 mOrientedRanges.haveToolSize = true;
3729 mOrientedRanges.haveSize = true;
3730
3731 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3732 mOrientedRanges.touchMajor.source = mSource;
3733 mOrientedRanges.touchMajor.min = 0;
3734 mOrientedRanges.touchMajor.max = diagonalSize;
3735 mOrientedRanges.touchMajor.flat = 0;
3736 mOrientedRanges.touchMajor.fuzz = 0;
3737 mOrientedRanges.touchMajor.resolution = 0;
3738
3739 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3740 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3741
3742 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3743 mOrientedRanges.toolMajor.source = mSource;
3744 mOrientedRanges.toolMajor.min = 0;
3745 mOrientedRanges.toolMajor.max = diagonalSize;
3746 mOrientedRanges.toolMajor.flat = 0;
3747 mOrientedRanges.toolMajor.fuzz = 0;
3748 mOrientedRanges.toolMajor.resolution = 0;
3749
3750 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3751 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3752
3753 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3754 mOrientedRanges.size.source = mSource;
3755 mOrientedRanges.size.min = 0;
3756 mOrientedRanges.size.max = 1.0;
3757 mOrientedRanges.size.flat = 0;
3758 mOrientedRanges.size.fuzz = 0;
3759 mOrientedRanges.size.resolution = 0;
3760 } else {
3761 mSizeScale = 0.0f;
3762 }
3763
3764 // Pressure factors.
3765 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003766 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3768 || mCalibration.pressureCalibration
3769 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3770 if (mCalibration.havePressureScale) {
3771 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003772 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003773 } else if (mRawPointerAxes.pressure.valid
3774 && mRawPointerAxes.pressure.maxValue != 0) {
3775 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3776 }
3777 }
3778
3779 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3780 mOrientedRanges.pressure.source = mSource;
3781 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003782 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003783 mOrientedRanges.pressure.flat = 0;
3784 mOrientedRanges.pressure.fuzz = 0;
3785 mOrientedRanges.pressure.resolution = 0;
3786
3787 // Tilt
3788 mTiltXCenter = 0;
3789 mTiltXScale = 0;
3790 mTiltYCenter = 0;
3791 mTiltYScale = 0;
3792 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3793 if (mHaveTilt) {
3794 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3795 mRawPointerAxes.tiltX.maxValue);
3796 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3797 mRawPointerAxes.tiltY.maxValue);
3798 mTiltXScale = M_PI / 180;
3799 mTiltYScale = M_PI / 180;
3800
3801 mOrientedRanges.haveTilt = true;
3802
3803 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3804 mOrientedRanges.tilt.source = mSource;
3805 mOrientedRanges.tilt.min = 0;
3806 mOrientedRanges.tilt.max = M_PI_2;
3807 mOrientedRanges.tilt.flat = 0;
3808 mOrientedRanges.tilt.fuzz = 0;
3809 mOrientedRanges.tilt.resolution = 0;
3810 }
3811
3812 // Orientation
3813 mOrientationScale = 0;
3814 if (mHaveTilt) {
3815 mOrientedRanges.haveOrientation = true;
3816
3817 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3818 mOrientedRanges.orientation.source = mSource;
3819 mOrientedRanges.orientation.min = -M_PI;
3820 mOrientedRanges.orientation.max = M_PI;
3821 mOrientedRanges.orientation.flat = 0;
3822 mOrientedRanges.orientation.fuzz = 0;
3823 mOrientedRanges.orientation.resolution = 0;
3824 } else if (mCalibration.orientationCalibration !=
3825 Calibration::ORIENTATION_CALIBRATION_NONE) {
3826 if (mCalibration.orientationCalibration
3827 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3828 if (mRawPointerAxes.orientation.valid) {
3829 if (mRawPointerAxes.orientation.maxValue > 0) {
3830 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3831 } else if (mRawPointerAxes.orientation.minValue < 0) {
3832 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3833 } else {
3834 mOrientationScale = 0;
3835 }
3836 }
3837 }
3838
3839 mOrientedRanges.haveOrientation = true;
3840
3841 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3842 mOrientedRanges.orientation.source = mSource;
3843 mOrientedRanges.orientation.min = -M_PI_2;
3844 mOrientedRanges.orientation.max = M_PI_2;
3845 mOrientedRanges.orientation.flat = 0;
3846 mOrientedRanges.orientation.fuzz = 0;
3847 mOrientedRanges.orientation.resolution = 0;
3848 }
3849
3850 // Distance
3851 mDistanceScale = 0;
3852 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3853 if (mCalibration.distanceCalibration
3854 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3855 if (mCalibration.haveDistanceScale) {
3856 mDistanceScale = mCalibration.distanceScale;
3857 } else {
3858 mDistanceScale = 1.0f;
3859 }
3860 }
3861
3862 mOrientedRanges.haveDistance = true;
3863
3864 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3865 mOrientedRanges.distance.source = mSource;
3866 mOrientedRanges.distance.min =
3867 mRawPointerAxes.distance.minValue * mDistanceScale;
3868 mOrientedRanges.distance.max =
3869 mRawPointerAxes.distance.maxValue * mDistanceScale;
3870 mOrientedRanges.distance.flat = 0;
3871 mOrientedRanges.distance.fuzz =
3872 mRawPointerAxes.distance.fuzz * mDistanceScale;
3873 mOrientedRanges.distance.resolution = 0;
3874 }
3875
3876 // Compute oriented precision, scales and ranges.
3877 // Note that the maximum value reported is an inclusive maximum value so it is one
3878 // unit less than the total width or height of surface.
3879 switch (mSurfaceOrientation) {
3880 case DISPLAY_ORIENTATION_90:
3881 case DISPLAY_ORIENTATION_270:
3882 mOrientedXPrecision = mYPrecision;
3883 mOrientedYPrecision = mXPrecision;
3884
3885 mOrientedRanges.x.min = mYTranslate;
3886 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3887 mOrientedRanges.x.flat = 0;
3888 mOrientedRanges.x.fuzz = 0;
3889 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3890
3891 mOrientedRanges.y.min = mXTranslate;
3892 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3893 mOrientedRanges.y.flat = 0;
3894 mOrientedRanges.y.fuzz = 0;
3895 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3896 break;
3897
3898 default:
3899 mOrientedXPrecision = mXPrecision;
3900 mOrientedYPrecision = mYPrecision;
3901
3902 mOrientedRanges.x.min = mXTranslate;
3903 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3904 mOrientedRanges.x.flat = 0;
3905 mOrientedRanges.x.fuzz = 0;
3906 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3907
3908 mOrientedRanges.y.min = mYTranslate;
3909 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3910 mOrientedRanges.y.flat = 0;
3911 mOrientedRanges.y.fuzz = 0;
3912 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3913 break;
3914 }
3915
Jason Gerecke71b16e82014-03-10 09:47:59 -07003916 // Location
3917 updateAffineTransformation();
3918
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 if (mDeviceMode == DEVICE_MODE_POINTER) {
3920 // Compute pointer gesture detection parameters.
3921 float rawDiagonal = hypotf(rawWidth, rawHeight);
3922 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3923
3924 // Scale movements such that one whole swipe of the touch pad covers a
3925 // given area relative to the diagonal size of the display when no acceleration
3926 // is applied.
3927 // Assume that the touch pad has a square aspect ratio such that movements in
3928 // X and Y of the same number of raw units cover the same physical distance.
3929 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3930 * displayDiagonal / rawDiagonal;
3931 mPointerYMovementScale = mPointerXMovementScale;
3932
3933 // Scale zooms to cover a smaller range of the display than movements do.
3934 // This value determines the area around the pointer that is affected by freeform
3935 // pointer gestures.
3936 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3937 * displayDiagonal / rawDiagonal;
3938 mPointerYZoomScale = mPointerXZoomScale;
3939
3940 // Max width between pointers to detect a swipe gesture is more than some fraction
3941 // of the diagonal axis of the touch pad. Touches that are wider than this are
3942 // translated into freeform gestures.
3943 mPointerGestureMaxSwipeWidth =
3944 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3945
3946 // Abort current pointer usages because the state has changed.
3947 abortPointerUsage(when, 0 /*policyFlags*/);
3948 }
3949
3950 // Inform the dispatcher about the changes.
3951 *outResetNeeded = true;
3952 bumpGeneration();
3953 }
3954}
3955
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003956void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003957 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003958 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3959 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3960 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3961 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003962 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3963 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3964 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3965 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003966 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967}
3968
3969void TouchInputMapper::configureVirtualKeys() {
3970 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3971 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3972
3973 mVirtualKeys.clear();
3974
3975 if (virtualKeyDefinitions.size() == 0) {
3976 return;
3977 }
3978
3979 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3980
3981 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3982 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003983 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3984 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003985
3986 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3987 const VirtualKeyDefinition& virtualKeyDefinition =
3988 virtualKeyDefinitions[i];
3989
3990 mVirtualKeys.add();
3991 VirtualKey& virtualKey = mVirtualKeys.editTop();
3992
3993 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3994 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003995 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003996 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003997 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3998 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
4000 virtualKey.scanCode);
4001 mVirtualKeys.pop(); // drop the key
4002 continue;
4003 }
4004
4005 virtualKey.keyCode = keyCode;
4006 virtualKey.flags = flags;
4007
4008 // convert the key definition's display coordinates into touch coordinates for a hit box
4009 int32_t halfWidth = virtualKeyDefinition.width / 2;
4010 int32_t halfHeight = virtualKeyDefinition.height / 2;
4011
4012 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
4013 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
4014 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
4015 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
4016 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
4017 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
4018 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
4019 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
4020 }
4021}
4022
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004023void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004024 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004025 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004026
4027 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
4028 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004029 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4031 i, virtualKey.scanCode, virtualKey.keyCode,
4032 virtualKey.hitLeft, virtualKey.hitRight,
4033 virtualKey.hitTop, virtualKey.hitBottom);
4034 }
4035 }
4036}
4037
4038void TouchInputMapper::parseCalibration() {
4039 const PropertyMap& in = getDevice()->getConfiguration();
4040 Calibration& out = mCalibration;
4041
4042 // Size
4043 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4044 String8 sizeCalibrationString;
4045 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4046 if (sizeCalibrationString == "none") {
4047 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4048 } else if (sizeCalibrationString == "geometric") {
4049 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4050 } else if (sizeCalibrationString == "diameter") {
4051 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4052 } else if (sizeCalibrationString == "box") {
4053 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4054 } else if (sizeCalibrationString == "area") {
4055 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4056 } else if (sizeCalibrationString != "default") {
4057 ALOGW("Invalid value for touch.size.calibration: '%s'",
4058 sizeCalibrationString.string());
4059 }
4060 }
4061
4062 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4063 out.sizeScale);
4064 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4065 out.sizeBias);
4066 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4067 out.sizeIsSummed);
4068
4069 // Pressure
4070 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4071 String8 pressureCalibrationString;
4072 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4073 if (pressureCalibrationString == "none") {
4074 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4075 } else if (pressureCalibrationString == "physical") {
4076 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4077 } else if (pressureCalibrationString == "amplitude") {
4078 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4079 } else if (pressureCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4081 pressureCalibrationString.string());
4082 }
4083 }
4084
4085 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4086 out.pressureScale);
4087
4088 // Orientation
4089 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4090 String8 orientationCalibrationString;
4091 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4092 if (orientationCalibrationString == "none") {
4093 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4094 } else if (orientationCalibrationString == "interpolated") {
4095 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4096 } else if (orientationCalibrationString == "vector") {
4097 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4098 } else if (orientationCalibrationString != "default") {
4099 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4100 orientationCalibrationString.string());
4101 }
4102 }
4103
4104 // Distance
4105 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4106 String8 distanceCalibrationString;
4107 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4108 if (distanceCalibrationString == "none") {
4109 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4110 } else if (distanceCalibrationString == "scaled") {
4111 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4112 } else if (distanceCalibrationString != "default") {
4113 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4114 distanceCalibrationString.string());
4115 }
4116 }
4117
4118 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4119 out.distanceScale);
4120
4121 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4122 String8 coverageCalibrationString;
4123 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4124 if (coverageCalibrationString == "none") {
4125 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4126 } else if (coverageCalibrationString == "box") {
4127 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4128 } else if (coverageCalibrationString != "default") {
4129 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4130 coverageCalibrationString.string());
4131 }
4132 }
4133}
4134
4135void TouchInputMapper::resolveCalibration() {
4136 // Size
4137 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4138 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4139 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4140 }
4141 } else {
4142 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4143 }
4144
4145 // Pressure
4146 if (mRawPointerAxes.pressure.valid) {
4147 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4148 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4149 }
4150 } else {
4151 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4152 }
4153
4154 // Orientation
4155 if (mRawPointerAxes.orientation.valid) {
4156 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4157 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4158 }
4159 } else {
4160 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4161 }
4162
4163 // Distance
4164 if (mRawPointerAxes.distance.valid) {
4165 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4166 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4167 }
4168 } else {
4169 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4170 }
4171
4172 // Coverage
4173 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4174 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4175 }
4176}
4177
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178void TouchInputMapper::dumpCalibration(std::string& dump) {
4179 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180
4181 // Size
4182 switch (mCalibration.sizeCalibration) {
4183 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 break;
4186 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004187 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 break;
4189 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004190 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 break;
4192 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 break;
4195 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004196 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004197 break;
4198 default:
4199 ALOG_ASSERT(false);
4200 }
4201
4202 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004203 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004204 mCalibration.sizeScale);
4205 }
4206
4207 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 mCalibration.sizeBias);
4210 }
4211
4212 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 toString(mCalibration.sizeIsSummed));
4215 }
4216
4217 // Pressure
4218 switch (mCalibration.pressureCalibration) {
4219 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004221 break;
4222 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004224 break;
4225 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004226 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004227 break;
4228 default:
4229 ALOG_ASSERT(false);
4230 }
4231
4232 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 mCalibration.pressureScale);
4235 }
4236
4237 // Orientation
4238 switch (mCalibration.orientationCalibration) {
4239 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004240 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004241 break;
4242 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 break;
4245 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 break;
4248 default:
4249 ALOG_ASSERT(false);
4250 }
4251
4252 // Distance
4253 switch (mCalibration.distanceCalibration) {
4254 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004255 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256 break;
4257 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004258 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259 break;
4260 default:
4261 ALOG_ASSERT(false);
4262 }
4263
4264 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004265 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 mCalibration.distanceScale);
4267 }
4268
4269 switch (mCalibration.coverageCalibration) {
4270 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004271 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 break;
4273 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004274 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 break;
4276 default:
4277 ALOG_ASSERT(false);
4278 }
4279}
4280
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004281void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4282 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004283
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004284 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4285 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4286 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4287 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4288 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4289 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004290}
4291
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004292void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004293 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4294 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004295}
4296
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297void TouchInputMapper::reset(nsecs_t when) {
4298 mCursorButtonAccumulator.reset(getDevice());
4299 mCursorScrollAccumulator.reset(getDevice());
4300 mTouchButtonAccumulator.reset(getDevice());
4301
4302 mPointerVelocityControl.reset();
4303 mWheelXVelocityControl.reset();
4304 mWheelYVelocityControl.reset();
4305
Michael Wright842500e2015-03-13 17:32:02 -07004306 mRawStatesPending.clear();
4307 mCurrentRawState.clear();
4308 mCurrentCookedState.clear();
4309 mLastRawState.clear();
4310 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004311 mPointerUsage = POINTER_USAGE_NONE;
4312 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004313 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004314 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004315 mDownTime = 0;
4316
4317 mCurrentVirtualKey.down = false;
4318
4319 mPointerGesture.reset();
4320 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004321 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004322
Yi Kong9b14ac62018-07-17 13:48:38 -07004323 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004324 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4325 mPointerController->clearSpots();
4326 }
4327
4328 InputMapper::reset(when);
4329}
4330
Michael Wright842500e2015-03-13 17:32:02 -07004331void TouchInputMapper::resetExternalStylus() {
4332 mExternalStylusState.clear();
4333 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004334 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004335 mExternalStylusDataPending = false;
4336}
4337
Michael Wright43fd19f2015-04-21 19:02:58 +01004338void TouchInputMapper::clearStylusDataPendingFlags() {
4339 mExternalStylusDataPending = false;
4340 mExternalStylusFusionTimeout = LLONG_MAX;
4341}
4342
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004343void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4344 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4345 nsecs_t latency = now - evdevTime;
4346 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4347 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4348 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4349 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
4350 mStatistics.min, mStatistics.max, mStatistics.mean(), mStatistics.stdev());
4351 mStatistics.reset(now);
4352 }
4353}
4354
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355void TouchInputMapper::process(const RawEvent* rawEvent) {
4356 mCursorButtonAccumulator.process(rawEvent);
4357 mCursorScrollAccumulator.process(rawEvent);
4358 mTouchButtonAccumulator.process(rawEvent);
4359
4360 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004361 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004362 sync(rawEvent->when);
4363 }
4364}
4365
4366void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004367 const RawState* last = mRawStatesPending.isEmpty() ?
4368 &mCurrentRawState : &mRawStatesPending.top();
4369
4370 // Push a new state.
4371 mRawStatesPending.push();
4372 RawState* next = &mRawStatesPending.editTop();
4373 next->clear();
4374 next->when = when;
4375
Michael Wrightd02c5b62014-02-10 15:10:22 -08004376 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004377 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004378 | mCursorButtonAccumulator.getButtonState();
4379
Michael Wright842500e2015-03-13 17:32:02 -07004380 // Sync scroll
4381 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4382 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004383 mCursorScrollAccumulator.finishSync();
4384
Michael Wright842500e2015-03-13 17:32:02 -07004385 // Sync touch
4386 syncTouch(when, next);
4387
4388 // Assign pointer ids.
4389 if (!mHavePointerIds) {
4390 assignPointerIds(last, next);
4391 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004392
4393#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004394 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4395 "hovering ids 0x%08x -> 0x%08x",
4396 last->rawPointerData.pointerCount,
4397 next->rawPointerData.pointerCount,
4398 last->rawPointerData.touchingIdBits.value,
4399 next->rawPointerData.touchingIdBits.value,
4400 last->rawPointerData.hoveringIdBits.value,
4401 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004402#endif
4403
Michael Wright842500e2015-03-13 17:32:02 -07004404 processRawTouches(false /*timeout*/);
4405}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004406
Michael Wright842500e2015-03-13 17:32:02 -07004407void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004408 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4409 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004410 mCurrentRawState.clear();
4411 mRawStatesPending.clear();
4412 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004413 }
4414
Michael Wright842500e2015-03-13 17:32:02 -07004415 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4416 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4417 // touching the current state will only observe the events that have been dispatched to the
4418 // rest of the pipeline.
4419 const size_t N = mRawStatesPending.size();
4420 size_t count;
4421 for(count = 0; count < N; count++) {
4422 const RawState& next = mRawStatesPending[count];
4423
4424 // A failure to assign the stylus id means that we're waiting on stylus data
4425 // and so should defer the rest of the pipeline.
4426 if (assignExternalStylusId(next, timeout)) {
4427 break;
4428 }
4429
4430 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004431 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004432 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004433 if (mCurrentRawState.when < mLastRawState.when) {
4434 mCurrentRawState.when = mLastRawState.when;
4435 }
Michael Wright842500e2015-03-13 17:32:02 -07004436 cookAndDispatch(mCurrentRawState.when);
4437 }
4438 if (count != 0) {
4439 mRawStatesPending.removeItemsAt(0, count);
4440 }
4441
Michael Wright842500e2015-03-13 17:32:02 -07004442 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004443 if (timeout) {
4444 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4445 clearStylusDataPendingFlags();
4446 mCurrentRawState.copyFrom(mLastRawState);
4447#if DEBUG_STYLUS_FUSION
4448 ALOGD("Timeout expired, synthesizing event with new stylus data");
4449#endif
4450 cookAndDispatch(when);
4451 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4452 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4453 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4454 }
Michael Wright842500e2015-03-13 17:32:02 -07004455 }
4456}
4457
4458void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4459 // Always start with a clean state.
4460 mCurrentCookedState.clear();
4461
4462 // Apply stylus buttons to current raw state.
4463 applyExternalStylusButtonState(when);
4464
4465 // Handle policy on initial down or hover events.
4466 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4467 && mCurrentRawState.rawPointerData.pointerCount != 0;
4468
4469 uint32_t policyFlags = 0;
4470 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4471 if (initialDown || buttonsPressed) {
4472 // If this is a touch screen, hide the pointer on an initial down.
4473 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4474 getContext()->fadePointer();
4475 }
4476
4477 if (mParameters.wake) {
4478 policyFlags |= POLICY_FLAG_WAKE;
4479 }
4480 }
4481
4482 // Consume raw off-screen touches before cooking pointer data.
4483 // If touches are consumed, subsequent code will not receive any pointer data.
4484 if (consumeRawTouches(when, policyFlags)) {
4485 mCurrentRawState.rawPointerData.clear();
4486 }
4487
4488 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4489 // with cooked pointer data that has the same ids and indices as the raw data.
4490 // The following code can use either the raw or cooked data, as needed.
4491 cookPointerData();
4492
4493 // Apply stylus pressure to current cooked state.
4494 applyExternalStylusTouchState(when);
4495
4496 // Synthesize key down from raw buttons if needed.
4497 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004498 mViewport.displayId, policyFlags,
4499 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004500
4501 // Dispatch the touches either directly or by translation through a pointer on screen.
4502 if (mDeviceMode == DEVICE_MODE_POINTER) {
4503 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4504 !idBits.isEmpty(); ) {
4505 uint32_t id = idBits.clearFirstMarkedBit();
4506 const RawPointerData::Pointer& pointer =
4507 mCurrentRawState.rawPointerData.pointerForId(id);
4508 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4509 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4510 mCurrentCookedState.stylusIdBits.markBit(id);
4511 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4512 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4513 mCurrentCookedState.fingerIdBits.markBit(id);
4514 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4515 mCurrentCookedState.mouseIdBits.markBit(id);
4516 }
4517 }
4518 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4519 !idBits.isEmpty(); ) {
4520 uint32_t id = idBits.clearFirstMarkedBit();
4521 const RawPointerData::Pointer& pointer =
4522 mCurrentRawState.rawPointerData.pointerForId(id);
4523 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4524 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4525 mCurrentCookedState.stylusIdBits.markBit(id);
4526 }
4527 }
4528
4529 // Stylus takes precedence over all tools, then mouse, then finger.
4530 PointerUsage pointerUsage = mPointerUsage;
4531 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4532 mCurrentCookedState.mouseIdBits.clear();
4533 mCurrentCookedState.fingerIdBits.clear();
4534 pointerUsage = POINTER_USAGE_STYLUS;
4535 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4536 mCurrentCookedState.fingerIdBits.clear();
4537 pointerUsage = POINTER_USAGE_MOUSE;
4538 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4539 isPointerDown(mCurrentRawState.buttonState)) {
4540 pointerUsage = POINTER_USAGE_GESTURES;
4541 }
4542
4543 dispatchPointerUsage(when, policyFlags, pointerUsage);
4544 } else {
4545 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004546 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004547 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4548 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4549
4550 mPointerController->setButtonState(mCurrentRawState.buttonState);
4551 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4552 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004553 mCurrentCookedState.cookedPointerData.touchingIdBits,
4554 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004555 }
4556
Michael Wright8e812822015-06-22 16:18:21 +01004557 if (!mCurrentMotionAborted) {
4558 dispatchButtonRelease(when, policyFlags);
4559 dispatchHoverExit(when, policyFlags);
4560 dispatchTouches(when, policyFlags);
4561 dispatchHoverEnterAndMove(when, policyFlags);
4562 dispatchButtonPress(when, policyFlags);
4563 }
4564
4565 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4566 mCurrentMotionAborted = false;
4567 }
Michael Wright842500e2015-03-13 17:32:02 -07004568 }
4569
4570 // Synthesize key up from raw buttons if needed.
4571 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004572 mViewport.displayId, policyFlags,
4573 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004574
4575 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004576 mCurrentRawState.rawVScroll = 0;
4577 mCurrentRawState.rawHScroll = 0;
4578
4579 // Copy current touch to last touch in preparation for the next cycle.
4580 mLastRawState.copyFrom(mCurrentRawState);
4581 mLastCookedState.copyFrom(mCurrentCookedState);
4582}
4583
4584void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004585 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004586 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4587 }
4588}
4589
4590void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004591 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4592 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004593
Michael Wright53dca3a2015-04-23 17:39:53 +01004594 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4595 float pressure = mExternalStylusState.pressure;
4596 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4597 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4598 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4599 }
4600 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4601 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4602
4603 PointerProperties& properties =
4604 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004605 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4606 properties.toolType = mExternalStylusState.toolType;
4607 }
4608 }
4609}
4610
4611bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4612 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4613 return false;
4614 }
4615
4616 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4617 && state.rawPointerData.pointerCount != 0;
4618 if (initialDown) {
4619 if (mExternalStylusState.pressure != 0.0f) {
4620#if DEBUG_STYLUS_FUSION
4621 ALOGD("Have both stylus and touch data, beginning fusion");
4622#endif
4623 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4624 } else if (timeout) {
4625#if DEBUG_STYLUS_FUSION
4626 ALOGD("Timeout expired, assuming touch is not a stylus.");
4627#endif
4628 resetExternalStylus();
4629 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004630 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4631 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004632 }
4633#if DEBUG_STYLUS_FUSION
4634 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004635 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004636#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004637 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004638 return true;
4639 }
4640 }
4641
4642 // Check if the stylus pointer has gone up.
4643 if (mExternalStylusId != -1 &&
4644 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4645#if DEBUG_STYLUS_FUSION
4646 ALOGD("Stylus pointer is going up");
4647#endif
4648 mExternalStylusId = -1;
4649 }
4650
4651 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652}
4653
4654void TouchInputMapper::timeoutExpired(nsecs_t when) {
4655 if (mDeviceMode == DEVICE_MODE_POINTER) {
4656 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4657 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4658 }
Michael Wright842500e2015-03-13 17:32:02 -07004659 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004660 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004661 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004662 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4663 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004664 }
4665 }
4666}
4667
4668void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004669 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004670 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004671 // We're either in the middle of a fused stream of data or we're waiting on data before
4672 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4673 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004674 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004675 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 }
4677}
4678
4679bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4680 // Check for release of a virtual key.
4681 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004682 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004683 // Pointer went up while virtual key was down.
4684 mCurrentVirtualKey.down = false;
4685 if (!mCurrentVirtualKey.ignored) {
4686#if DEBUG_VIRTUAL_KEYS
4687 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4688 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4689#endif
4690 dispatchVirtualKey(when, policyFlags,
4691 AKEY_EVENT_ACTION_UP,
4692 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4693 }
4694 return true;
4695 }
4696
Michael Wright842500e2015-03-13 17:32:02 -07004697 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4698 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4699 const RawPointerData::Pointer& pointer =
4700 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004701 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4702 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4703 // Pointer is still within the space of the virtual key.
4704 return true;
4705 }
4706 }
4707
4708 // Pointer left virtual key area or another pointer also went down.
4709 // Send key cancellation but do not consume the touch yet.
4710 // This is useful when the user swipes through from the virtual key area
4711 // into the main display surface.
4712 mCurrentVirtualKey.down = false;
4713 if (!mCurrentVirtualKey.ignored) {
4714#if DEBUG_VIRTUAL_KEYS
4715 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4716 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4717#endif
4718 dispatchVirtualKey(when, policyFlags,
4719 AKEY_EVENT_ACTION_UP,
4720 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4721 | AKEY_EVENT_FLAG_CANCELED);
4722 }
4723 }
4724
Michael Wright842500e2015-03-13 17:32:02 -07004725 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4726 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004727 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004728 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4729 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004730 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4731 // If exactly one pointer went down, check for virtual key hit.
4732 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004733 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4735 if (virtualKey) {
4736 mCurrentVirtualKey.down = true;
4737 mCurrentVirtualKey.downTime = when;
4738 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4739 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4740 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4741 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4742
4743 if (!mCurrentVirtualKey.ignored) {
4744#if DEBUG_VIRTUAL_KEYS
4745 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4746 mCurrentVirtualKey.keyCode,
4747 mCurrentVirtualKey.scanCode);
4748#endif
4749 dispatchVirtualKey(when, policyFlags,
4750 AKEY_EVENT_ACTION_DOWN,
4751 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4752 }
4753 }
4754 }
4755 return true;
4756 }
4757 }
4758
4759 // Disable all virtual key touches that happen within a short time interval of the
4760 // most recent touch within the screen area. The idea is to filter out stray
4761 // virtual key presses when interacting with the touch screen.
4762 //
4763 // Problems we're trying to solve:
4764 //
4765 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4766 // virtual key area that is implemented by a separate touch panel and accidentally
4767 // triggers a virtual key.
4768 //
4769 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4770 // area and accidentally triggers a virtual key. This often happens when virtual keys
4771 // are layed out below the screen near to where the on screen keyboard's space bar
4772 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004773 if (mConfig.virtualKeyQuietTime > 0 &&
4774 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4776 }
4777 return false;
4778}
4779
4780void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4781 int32_t keyEventAction, int32_t keyEventFlags) {
4782 int32_t keyCode = mCurrentVirtualKey.keyCode;
4783 int32_t scanCode = mCurrentVirtualKey.scanCode;
4784 nsecs_t downTime = mCurrentVirtualKey.downTime;
4785 int32_t metaState = mContext->getGlobalMetaState();
4786 policyFlags |= POLICY_FLAG_VIRTUAL;
4787
Prabir Pradhan42611e02018-11-27 14:04:02 -08004788 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4789 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004790 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 getListener()->notifyKey(&args);
4792}
4793
Michael Wright8e812822015-06-22 16:18:21 +01004794void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4795 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4796 if (!currentIdBits.isEmpty()) {
4797 int32_t metaState = getContext()->getGlobalMetaState();
4798 int32_t buttonState = mCurrentCookedState.buttonState;
4799 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4800 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004801 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004802 mCurrentCookedState.cookedPointerData.pointerProperties,
4803 mCurrentCookedState.cookedPointerData.pointerCoords,
4804 mCurrentCookedState.cookedPointerData.idToIndex,
4805 currentIdBits, -1,
4806 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4807 mCurrentMotionAborted = true;
4808 }
4809}
4810
Michael Wrightd02c5b62014-02-10 15:10:22 -08004811void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004812 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4813 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004815 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004816
4817 if (currentIdBits == lastIdBits) {
4818 if (!currentIdBits.isEmpty()) {
4819 // No pointer id changes so this is a move event.
4820 // The listener takes care of batching moves so we don't have to deal with that here.
4821 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004822 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004824 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004825 mCurrentCookedState.cookedPointerData.pointerProperties,
4826 mCurrentCookedState.cookedPointerData.pointerCoords,
4827 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 currentIdBits, -1,
4829 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4830 }
4831 } else {
4832 // There may be pointers going up and pointers going down and pointers moving
4833 // all at the same time.
4834 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4835 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4836 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4837 BitSet32 dispatchedIdBits(lastIdBits.value);
4838
4839 // Update last coordinates of pointers that have moved so that we observe the new
4840 // pointer positions at the same time as other pointers that have just gone up.
4841 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004842 mCurrentCookedState.cookedPointerData.pointerProperties,
4843 mCurrentCookedState.cookedPointerData.pointerCoords,
4844 mCurrentCookedState.cookedPointerData.idToIndex,
4845 mLastCookedState.cookedPointerData.pointerProperties,
4846 mLastCookedState.cookedPointerData.pointerCoords,
4847 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004849 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004850 moveNeeded = true;
4851 }
4852
4853 // Dispatch pointer up events.
4854 while (!upIdBits.isEmpty()) {
4855 uint32_t upId = upIdBits.clearFirstMarkedBit();
4856
4857 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004858 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004859 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004860 mLastCookedState.cookedPointerData.pointerProperties,
4861 mLastCookedState.cookedPointerData.pointerCoords,
4862 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004863 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 dispatchedIdBits.clearBit(upId);
4865 }
4866
4867 // Dispatch move events if any of the remaining pointers moved from their old locations.
4868 // Although applications receive new locations as part of individual pointer up
4869 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004870 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4872 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004873 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004874 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004875 mCurrentCookedState.cookedPointerData.pointerProperties,
4876 mCurrentCookedState.cookedPointerData.pointerCoords,
4877 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004878 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004879 }
4880
4881 // Dispatch pointer down events using the new pointer locations.
4882 while (!downIdBits.isEmpty()) {
4883 uint32_t downId = downIdBits.clearFirstMarkedBit();
4884 dispatchedIdBits.markBit(downId);
4885
4886 if (dispatchedIdBits.count() == 1) {
4887 // First pointer is going down. Set down time.
4888 mDownTime = when;
4889 }
4890
4891 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004892 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004893 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004894 mCurrentCookedState.cookedPointerData.pointerProperties,
4895 mCurrentCookedState.cookedPointerData.pointerCoords,
4896 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004897 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004898 }
4899 }
4900}
4901
4902void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4903 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004904 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4905 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004906 int32_t metaState = getContext()->getGlobalMetaState();
4907 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004908 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004909 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004910 mLastCookedState.cookedPointerData.pointerProperties,
4911 mLastCookedState.cookedPointerData.pointerCoords,
4912 mLastCookedState.cookedPointerData.idToIndex,
4913 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004914 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4915 mSentHoverEnter = false;
4916 }
4917}
4918
4919void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004920 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4921 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922 int32_t metaState = getContext()->getGlobalMetaState();
4923 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004924 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004925 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004926 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004927 mCurrentCookedState.cookedPointerData.pointerProperties,
4928 mCurrentCookedState.cookedPointerData.pointerCoords,
4929 mCurrentCookedState.cookedPointerData.idToIndex,
4930 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004931 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4932 mSentHoverEnter = true;
4933 }
4934
4935 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004936 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004937 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004938 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004939 mCurrentCookedState.cookedPointerData.pointerProperties,
4940 mCurrentCookedState.cookedPointerData.pointerCoords,
4941 mCurrentCookedState.cookedPointerData.idToIndex,
4942 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004943 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4944 }
4945}
4946
Michael Wright7b159c92015-05-14 14:48:03 +01004947void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4948 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4949 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4950 const int32_t metaState = getContext()->getGlobalMetaState();
4951 int32_t buttonState = mLastCookedState.buttonState;
4952 while (!releasedButtons.isEmpty()) {
4953 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4954 buttonState &= ~actionButton;
4955 dispatchMotion(when, policyFlags, mSource,
4956 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4957 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004958 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004959 mCurrentCookedState.cookedPointerData.pointerProperties,
4960 mCurrentCookedState.cookedPointerData.pointerCoords,
4961 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4962 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4963 }
4964}
4965
4966void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4967 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4968 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4969 const int32_t metaState = getContext()->getGlobalMetaState();
4970 int32_t buttonState = mLastCookedState.buttonState;
4971 while (!pressedButtons.isEmpty()) {
4972 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4973 buttonState |= actionButton;
4974 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4975 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004976 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004977 mCurrentCookedState.cookedPointerData.pointerProperties,
4978 mCurrentCookedState.cookedPointerData.pointerCoords,
4979 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4980 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4981 }
4982}
4983
4984const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4985 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4986 return cookedPointerData.touchingIdBits;
4987 }
4988 return cookedPointerData.hoveringIdBits;
4989}
4990
Michael Wrightd02c5b62014-02-10 15:10:22 -08004991void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004992 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004993
Michael Wright842500e2015-03-13 17:32:02 -07004994 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004995 mCurrentCookedState.deviceTimestamp =
4996 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004997 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4998 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4999 mCurrentRawState.rawPointerData.hoveringIdBits;
5000 mCurrentCookedState.cookedPointerData.touchingIdBits =
5001 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005002
Michael Wright7b159c92015-05-14 14:48:03 +01005003 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
5004 mCurrentCookedState.buttonState = 0;
5005 } else {
5006 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
5007 }
5008
Michael Wrightd02c5b62014-02-10 15:10:22 -08005009 // Walk through the the active pointers and map device coordinates onto
5010 // surface coordinates and adjust for display orientation.
5011 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07005012 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005013
5014 // Size
5015 float touchMajor, touchMinor, toolMajor, toolMinor, size;
5016 switch (mCalibration.sizeCalibration) {
5017 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
5018 case Calibration::SIZE_CALIBRATION_DIAMETER:
5019 case Calibration::SIZE_CALIBRATION_BOX:
5020 case Calibration::SIZE_CALIBRATION_AREA:
5021 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
5022 touchMajor = in.touchMajor;
5023 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
5024 toolMajor = in.toolMajor;
5025 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
5026 size = mRawPointerAxes.touchMinor.valid
5027 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5028 } else if (mRawPointerAxes.touchMajor.valid) {
5029 toolMajor = touchMajor = in.touchMajor;
5030 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
5031 ? in.touchMinor : in.touchMajor;
5032 size = mRawPointerAxes.touchMinor.valid
5033 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5034 } else if (mRawPointerAxes.toolMajor.valid) {
5035 touchMajor = toolMajor = in.toolMajor;
5036 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5037 ? in.toolMinor : in.toolMajor;
5038 size = mRawPointerAxes.toolMinor.valid
5039 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5040 } else {
5041 ALOG_ASSERT(false, "No touch or tool axes. "
5042 "Size calibration should have been resolved to NONE.");
5043 touchMajor = 0;
5044 touchMinor = 0;
5045 toolMajor = 0;
5046 toolMinor = 0;
5047 size = 0;
5048 }
5049
5050 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005051 uint32_t touchingCount =
5052 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 if (touchingCount > 1) {
5054 touchMajor /= touchingCount;
5055 touchMinor /= touchingCount;
5056 toolMajor /= touchingCount;
5057 toolMinor /= touchingCount;
5058 size /= touchingCount;
5059 }
5060 }
5061
5062 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5063 touchMajor *= mGeometricScale;
5064 touchMinor *= mGeometricScale;
5065 toolMajor *= mGeometricScale;
5066 toolMinor *= mGeometricScale;
5067 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5068 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5069 touchMinor = touchMajor;
5070 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5071 toolMinor = toolMajor;
5072 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5073 touchMinor = touchMajor;
5074 toolMinor = toolMajor;
5075 }
5076
5077 mCalibration.applySizeScaleAndBias(&touchMajor);
5078 mCalibration.applySizeScaleAndBias(&touchMinor);
5079 mCalibration.applySizeScaleAndBias(&toolMajor);
5080 mCalibration.applySizeScaleAndBias(&toolMinor);
5081 size *= mSizeScale;
5082 break;
5083 default:
5084 touchMajor = 0;
5085 touchMinor = 0;
5086 toolMajor = 0;
5087 toolMinor = 0;
5088 size = 0;
5089 break;
5090 }
5091
5092 // Pressure
5093 float pressure;
5094 switch (mCalibration.pressureCalibration) {
5095 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5096 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5097 pressure = in.pressure * mPressureScale;
5098 break;
5099 default:
5100 pressure = in.isHovering ? 0 : 1;
5101 break;
5102 }
5103
5104 // Tilt and Orientation
5105 float tilt;
5106 float orientation;
5107 if (mHaveTilt) {
5108 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5109 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5110 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5111 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5112 } else {
5113 tilt = 0;
5114
5115 switch (mCalibration.orientationCalibration) {
5116 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5117 orientation = in.orientation * mOrientationScale;
5118 break;
5119 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5120 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5121 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5122 if (c1 != 0 || c2 != 0) {
5123 orientation = atan2f(c1, c2) * 0.5f;
5124 float confidence = hypotf(c1, c2);
5125 float scale = 1.0f + confidence / 16.0f;
5126 touchMajor *= scale;
5127 touchMinor /= scale;
5128 toolMajor *= scale;
5129 toolMinor /= scale;
5130 } else {
5131 orientation = 0;
5132 }
5133 break;
5134 }
5135 default:
5136 orientation = 0;
5137 }
5138 }
5139
5140 // Distance
5141 float distance;
5142 switch (mCalibration.distanceCalibration) {
5143 case Calibration::DISTANCE_CALIBRATION_SCALED:
5144 distance = in.distance * mDistanceScale;
5145 break;
5146 default:
5147 distance = 0;
5148 }
5149
5150 // Coverage
5151 int32_t rawLeft, rawTop, rawRight, rawBottom;
5152 switch (mCalibration.coverageCalibration) {
5153 case Calibration::COVERAGE_CALIBRATION_BOX:
5154 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5155 rawRight = in.toolMinor & 0x0000ffff;
5156 rawBottom = in.toolMajor & 0x0000ffff;
5157 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5158 break;
5159 default:
5160 rawLeft = rawTop = rawRight = rawBottom = 0;
5161 break;
5162 }
5163
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005164 // Adjust X,Y coords for device calibration
5165 // TODO: Adjust coverage coords?
5166 float xTransformed = in.x, yTransformed = in.y;
5167 mAffineTransform.applyTo(xTransformed, yTransformed);
5168
5169 // Adjust X, Y, and coverage coords for surface orientation.
5170 float x, y;
5171 float left, top, right, bottom;
5172
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 switch (mSurfaceOrientation) {
5174 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005175 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5176 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5178 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5179 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5180 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5181 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005182 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005183 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5184 }
5185 break;
5186 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005187 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005188 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005189 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5190 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005191 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5192 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5193 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005194 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005195 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5196 }
5197 break;
5198 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005199 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005200 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005201 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5202 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5204 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5205 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005206 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005207 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5208 }
5209 break;
5210 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005211 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5212 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5214 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5215 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5216 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5217 break;
5218 }
5219
5220 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005221 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005222 out.clear();
5223 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5224 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5225 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5226 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5227 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5228 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5229 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5230 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5231 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5232 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5233 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5234 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5235 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5236 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5237 } else {
5238 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5239 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5240 }
5241
5242 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005243 PointerProperties& properties =
5244 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 uint32_t id = in.id;
5246 properties.clear();
5247 properties.id = id;
5248 properties.toolType = in.toolType;
5249
5250 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005251 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 }
5253}
5254
5255void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5256 PointerUsage pointerUsage) {
5257 if (pointerUsage != mPointerUsage) {
5258 abortPointerUsage(when, policyFlags);
5259 mPointerUsage = pointerUsage;
5260 }
5261
5262 switch (mPointerUsage) {
5263 case POINTER_USAGE_GESTURES:
5264 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5265 break;
5266 case POINTER_USAGE_STYLUS:
5267 dispatchPointerStylus(when, policyFlags);
5268 break;
5269 case POINTER_USAGE_MOUSE:
5270 dispatchPointerMouse(when, policyFlags);
5271 break;
5272 default:
5273 break;
5274 }
5275}
5276
5277void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5278 switch (mPointerUsage) {
5279 case POINTER_USAGE_GESTURES:
5280 abortPointerGestures(when, policyFlags);
5281 break;
5282 case POINTER_USAGE_STYLUS:
5283 abortPointerStylus(when, policyFlags);
5284 break;
5285 case POINTER_USAGE_MOUSE:
5286 abortPointerMouse(when, policyFlags);
5287 break;
5288 default:
5289 break;
5290 }
5291
5292 mPointerUsage = POINTER_USAGE_NONE;
5293}
5294
5295void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5296 bool isTimeout) {
5297 // Update current gesture coordinates.
5298 bool cancelPreviousGesture, finishPreviousGesture;
5299 bool sendEvents = preparePointerGestures(when,
5300 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5301 if (!sendEvents) {
5302 return;
5303 }
5304 if (finishPreviousGesture) {
5305 cancelPreviousGesture = false;
5306 }
5307
5308 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005309 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5310 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005311 if (finishPreviousGesture || cancelPreviousGesture) {
5312 mPointerController->clearSpots();
5313 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005314
5315 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5316 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5317 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005318 mPointerGesture.currentGestureIdBits,
5319 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005320 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 } else {
5322 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5323 }
5324
5325 // Show or hide the pointer if needed.
5326 switch (mPointerGesture.currentGestureMode) {
5327 case PointerGesture::NEUTRAL:
5328 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005329 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5330 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 // Remind the user of where the pointer is after finishing a gesture with spots.
5332 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5333 }
5334 break;
5335 case PointerGesture::TAP:
5336 case PointerGesture::TAP_DRAG:
5337 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5338 case PointerGesture::HOVER:
5339 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005340 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341 // Unfade the pointer when the current gesture manipulates the
5342 // area directly under the pointer.
5343 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5344 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005345 case PointerGesture::FREEFORM:
5346 // Fade the pointer when the current gesture manipulates a different
5347 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005348 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005349 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5350 } else {
5351 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5352 }
5353 break;
5354 }
5355
5356 // Send events!
5357 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005358 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359
5360 // Update last coordinates of pointers that have moved so that we observe the new
5361 // pointer positions at the same time as other pointers that have just gone up.
5362 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5363 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5364 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5365 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5366 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5367 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5368 bool moveNeeded = false;
5369 if (down && !cancelPreviousGesture && !finishPreviousGesture
5370 && !mPointerGesture.lastGestureIdBits.isEmpty()
5371 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5372 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5373 & mPointerGesture.lastGestureIdBits.value);
5374 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5375 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5376 mPointerGesture.lastGestureProperties,
5377 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5378 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005379 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 moveNeeded = true;
5381 }
5382 }
5383
5384 // Send motion events for all pointers that went up or were canceled.
5385 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5386 if (!dispatchedGestureIdBits.isEmpty()) {
5387 if (cancelPreviousGesture) {
5388 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005389 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005390 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005391 mPointerGesture.lastGestureProperties,
5392 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005393 dispatchedGestureIdBits, -1, 0,
5394 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395
5396 dispatchedGestureIdBits.clear();
5397 } else {
5398 BitSet32 upGestureIdBits;
5399 if (finishPreviousGesture) {
5400 upGestureIdBits = dispatchedGestureIdBits;
5401 } else {
5402 upGestureIdBits.value = dispatchedGestureIdBits.value
5403 & ~mPointerGesture.currentGestureIdBits.value;
5404 }
5405 while (!upGestureIdBits.isEmpty()) {
5406 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5407
5408 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005409 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005411 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005412 mPointerGesture.lastGestureProperties,
5413 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5414 dispatchedGestureIdBits, id,
5415 0, 0, mPointerGesture.downTime);
5416
5417 dispatchedGestureIdBits.clearBit(id);
5418 }
5419 }
5420 }
5421
5422 // Send motion events for all pointers that moved.
5423 if (moveNeeded) {
5424 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005425 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005426 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005427 mPointerGesture.currentGestureProperties,
5428 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5429 dispatchedGestureIdBits, -1,
5430 0, 0, mPointerGesture.downTime);
5431 }
5432
5433 // Send motion events for all pointers that went down.
5434 if (down) {
5435 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5436 & ~dispatchedGestureIdBits.value);
5437 while (!downGestureIdBits.isEmpty()) {
5438 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5439 dispatchedGestureIdBits.markBit(id);
5440
5441 if (dispatchedGestureIdBits.count() == 1) {
5442 mPointerGesture.downTime = when;
5443 }
5444
5445 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005446 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005447 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 mPointerGesture.currentGestureProperties,
5449 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5450 dispatchedGestureIdBits, id,
5451 0, 0, mPointerGesture.downTime);
5452 }
5453 }
5454
5455 // Send motion events for hover.
5456 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5457 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005458 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005459 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005460 mPointerGesture.currentGestureProperties,
5461 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5462 mPointerGesture.currentGestureIdBits, -1,
5463 0, 0, mPointerGesture.downTime);
5464 } else if (dispatchedGestureIdBits.isEmpty()
5465 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5466 // Synthesize a hover move event after all pointers go up to indicate that
5467 // the pointer is hovering again even if the user is not currently touching
5468 // the touch pad. This ensures that a view will receive a fresh hover enter
5469 // event after a tap.
5470 float x, y;
5471 mPointerController->getPosition(&x, &y);
5472
5473 PointerProperties pointerProperties;
5474 pointerProperties.clear();
5475 pointerProperties.id = 0;
5476 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5477
5478 PointerCoords pointerCoords;
5479 pointerCoords.clear();
5480 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5481 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5482
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005483 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005484 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005485 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005486 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005487 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005488 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005489 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 getListener()->notifyMotion(&args);
5491 }
5492
5493 // Update state.
5494 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5495 if (!down) {
5496 mPointerGesture.lastGestureIdBits.clear();
5497 } else {
5498 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5499 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5500 uint32_t id = idBits.clearFirstMarkedBit();
5501 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5502 mPointerGesture.lastGestureProperties[index].copyFrom(
5503 mPointerGesture.currentGestureProperties[index]);
5504 mPointerGesture.lastGestureCoords[index].copyFrom(
5505 mPointerGesture.currentGestureCoords[index]);
5506 mPointerGesture.lastGestureIdToIndex[id] = index;
5507 }
5508 }
5509}
5510
5511void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5512 // Cancel previously dispatches pointers.
5513 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5514 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005515 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005516 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005517 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005518 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005519 mPointerGesture.lastGestureProperties,
5520 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5521 mPointerGesture.lastGestureIdBits, -1,
5522 0, 0, mPointerGesture.downTime);
5523 }
5524
5525 // Reset the current pointer gesture.
5526 mPointerGesture.reset();
5527 mPointerVelocityControl.reset();
5528
5529 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005530 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5532 mPointerController->clearSpots();
5533 }
5534}
5535
5536bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5537 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5538 *outCancelPreviousGesture = false;
5539 *outFinishPreviousGesture = false;
5540
5541 // Handle TAP timeout.
5542 if (isTimeout) {
5543#if DEBUG_GESTURES
5544 ALOGD("Gestures: Processing timeout");
5545#endif
5546
5547 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5548 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5549 // The tap/drag timeout has not yet expired.
5550 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5551 + mConfig.pointerGestureTapDragInterval);
5552 } else {
5553 // The tap is finished.
5554#if DEBUG_GESTURES
5555 ALOGD("Gestures: TAP finished");
5556#endif
5557 *outFinishPreviousGesture = true;
5558
5559 mPointerGesture.activeGestureId = -1;
5560 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5561 mPointerGesture.currentGestureIdBits.clear();
5562
5563 mPointerVelocityControl.reset();
5564 return true;
5565 }
5566 }
5567
5568 // We did not handle this timeout.
5569 return false;
5570 }
5571
Michael Wright842500e2015-03-13 17:32:02 -07005572 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5573 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574
5575 // Update the velocity tracker.
5576 {
5577 VelocityTracker::Position positions[MAX_POINTERS];
5578 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005579 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005580 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005581 const RawPointerData::Pointer& pointer =
5582 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005583 positions[count].x = pointer.x * mPointerXMovementScale;
5584 positions[count].y = pointer.y * mPointerYMovementScale;
5585 }
5586 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005587 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005588 }
5589
5590 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5591 // to NEUTRAL, then we should not generate tap event.
5592 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5593 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5594 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5595 mPointerGesture.resetTap();
5596 }
5597
5598 // Pick a new active touch id if needed.
5599 // Choose an arbitrary pointer that just went down, if there is one.
5600 // Otherwise choose an arbitrary remaining pointer.
5601 // This guarantees we always have an active touch id when there is at least one pointer.
5602 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005603 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5604 int32_t activeTouchId = lastActiveTouchId;
5605 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005606 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005608 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005609 mPointerGesture.firstTouchTime = when;
5610 }
Michael Wright842500e2015-03-13 17:32:02 -07005611 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005612 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005614 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005615 } else {
5616 activeTouchId = mPointerGesture.activeTouchId = -1;
5617 }
5618 }
5619
5620 // Determine whether we are in quiet time.
5621 bool isQuietTime = false;
5622 if (activeTouchId < 0) {
5623 mPointerGesture.resetQuietTime();
5624 } else {
5625 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5626 if (!isQuietTime) {
5627 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5628 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5629 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5630 && currentFingerCount < 2) {
5631 // Enter quiet time when exiting swipe or freeform state.
5632 // This is to prevent accidentally entering the hover state and flinging the
5633 // pointer when finishing a swipe and there is still one pointer left onscreen.
5634 isQuietTime = true;
5635 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5636 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005637 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005638 // Enter quiet time when releasing the button and there are still two or more
5639 // fingers down. This may indicate that one finger was used to press the button
5640 // but it has not gone up yet.
5641 isQuietTime = true;
5642 }
5643 if (isQuietTime) {
5644 mPointerGesture.quietTime = when;
5645 }
5646 }
5647 }
5648
5649 // Switch states based on button and pointer state.
5650 if (isQuietTime) {
5651 // Case 1: Quiet time. (QUIET)
5652#if DEBUG_GESTURES
5653 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5654 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5655#endif
5656 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5657 *outFinishPreviousGesture = true;
5658 }
5659
5660 mPointerGesture.activeGestureId = -1;
5661 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5662 mPointerGesture.currentGestureIdBits.clear();
5663
5664 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005665 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5667 // The pointer follows the active touch point.
5668 // Emit DOWN, MOVE, UP events at the pointer location.
5669 //
5670 // Only the active touch matters; other fingers are ignored. This policy helps
5671 // to handle the case where the user places a second finger on the touch pad
5672 // to apply the necessary force to depress an integrated button below the surface.
5673 // We don't want the second finger to be delivered to applications.
5674 //
5675 // For this to work well, we need to make sure to track the pointer that is really
5676 // active. If the user first puts one finger down to click then adds another
5677 // finger to drag then the active pointer should switch to the finger that is
5678 // being dragged.
5679#if DEBUG_GESTURES
5680 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5681 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5682#endif
5683 // Reset state when just starting.
5684 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5685 *outFinishPreviousGesture = true;
5686 mPointerGesture.activeGestureId = 0;
5687 }
5688
5689 // Switch pointers if needed.
5690 // Find the fastest pointer and follow it.
5691 if (activeTouchId >= 0 && currentFingerCount > 1) {
5692 int32_t bestId = -1;
5693 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005694 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005695 uint32_t id = idBits.clearFirstMarkedBit();
5696 float vx, vy;
5697 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5698 float speed = hypotf(vx, vy);
5699 if (speed > bestSpeed) {
5700 bestId = id;
5701 bestSpeed = speed;
5702 }
5703 }
5704 }
5705 if (bestId >= 0 && bestId != activeTouchId) {
5706 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005707#if DEBUG_GESTURES
5708 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5709 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5710#endif
5711 }
5712 }
5713
Jun Mukaifa1706a2015-12-03 01:14:46 -08005714 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005715 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005717 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005719 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005720 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5721 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722
5723 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5724 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5725
5726 // Move the pointer using a relative motion.
5727 // When using spots, the click will occur at the position of the anchor
5728 // spot and all other spots will move there.
5729 mPointerController->move(deltaX, deltaY);
5730 } else {
5731 mPointerVelocityControl.reset();
5732 }
5733
5734 float x, y;
5735 mPointerController->getPosition(&x, &y);
5736
5737 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5738 mPointerGesture.currentGestureIdBits.clear();
5739 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5740 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5741 mPointerGesture.currentGestureProperties[0].clear();
5742 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5743 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5744 mPointerGesture.currentGestureCoords[0].clear();
5745 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5746 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5747 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5748 } else if (currentFingerCount == 0) {
5749 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5750 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5751 *outFinishPreviousGesture = true;
5752 }
5753
5754 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5755 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5756 bool tapped = false;
5757 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5758 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5759 && lastFingerCount == 1) {
5760 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5761 float x, y;
5762 mPointerController->getPosition(&x, &y);
5763 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5764 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5765#if DEBUG_GESTURES
5766 ALOGD("Gestures: TAP");
5767#endif
5768
5769 mPointerGesture.tapUpTime = when;
5770 getContext()->requestTimeoutAtTime(when
5771 + mConfig.pointerGestureTapDragInterval);
5772
5773 mPointerGesture.activeGestureId = 0;
5774 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5775 mPointerGesture.currentGestureIdBits.clear();
5776 mPointerGesture.currentGestureIdBits.markBit(
5777 mPointerGesture.activeGestureId);
5778 mPointerGesture.currentGestureIdToIndex[
5779 mPointerGesture.activeGestureId] = 0;
5780 mPointerGesture.currentGestureProperties[0].clear();
5781 mPointerGesture.currentGestureProperties[0].id =
5782 mPointerGesture.activeGestureId;
5783 mPointerGesture.currentGestureProperties[0].toolType =
5784 AMOTION_EVENT_TOOL_TYPE_FINGER;
5785 mPointerGesture.currentGestureCoords[0].clear();
5786 mPointerGesture.currentGestureCoords[0].setAxisValue(
5787 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5788 mPointerGesture.currentGestureCoords[0].setAxisValue(
5789 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5790 mPointerGesture.currentGestureCoords[0].setAxisValue(
5791 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5792
5793 tapped = true;
5794 } else {
5795#if DEBUG_GESTURES
5796 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5797 x - mPointerGesture.tapX,
5798 y - mPointerGesture.tapY);
5799#endif
5800 }
5801 } else {
5802#if DEBUG_GESTURES
5803 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5804 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5805 (when - mPointerGesture.tapDownTime) * 0.000001f);
5806 } else {
5807 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5808 }
5809#endif
5810 }
5811 }
5812
5813 mPointerVelocityControl.reset();
5814
5815 if (!tapped) {
5816#if DEBUG_GESTURES
5817 ALOGD("Gestures: NEUTRAL");
5818#endif
5819 mPointerGesture.activeGestureId = -1;
5820 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5821 mPointerGesture.currentGestureIdBits.clear();
5822 }
5823 } else if (currentFingerCount == 1) {
5824 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5825 // The pointer follows the active touch point.
5826 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5827 // When in TAP_DRAG, emit MOVE events at the pointer location.
5828 ALOG_ASSERT(activeTouchId >= 0);
5829
5830 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5831 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5832 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5833 float x, y;
5834 mPointerController->getPosition(&x, &y);
5835 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5836 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5837 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5838 } else {
5839#if DEBUG_GESTURES
5840 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5841 x - mPointerGesture.tapX,
5842 y - mPointerGesture.tapY);
5843#endif
5844 }
5845 } else {
5846#if DEBUG_GESTURES
5847 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5848 (when - mPointerGesture.tapUpTime) * 0.000001f);
5849#endif
5850 }
5851 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5852 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5853 }
5854
Jun Mukaifa1706a2015-12-03 01:14:46 -08005855 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005856 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005858 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005859 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005860 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005861 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5862 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005863
5864 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5865 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5866
5867 // Move the pointer using a relative motion.
5868 // When using spots, the hover or drag will occur at the position of the anchor spot.
5869 mPointerController->move(deltaX, deltaY);
5870 } else {
5871 mPointerVelocityControl.reset();
5872 }
5873
5874 bool down;
5875 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5876#if DEBUG_GESTURES
5877 ALOGD("Gestures: TAP_DRAG");
5878#endif
5879 down = true;
5880 } else {
5881#if DEBUG_GESTURES
5882 ALOGD("Gestures: HOVER");
5883#endif
5884 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5885 *outFinishPreviousGesture = true;
5886 }
5887 mPointerGesture.activeGestureId = 0;
5888 down = false;
5889 }
5890
5891 float x, y;
5892 mPointerController->getPosition(&x, &y);
5893
5894 mPointerGesture.currentGestureIdBits.clear();
5895 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5896 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5897 mPointerGesture.currentGestureProperties[0].clear();
5898 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5899 mPointerGesture.currentGestureProperties[0].toolType =
5900 AMOTION_EVENT_TOOL_TYPE_FINGER;
5901 mPointerGesture.currentGestureCoords[0].clear();
5902 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5903 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5904 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5905 down ? 1.0f : 0.0f);
5906
5907 if (lastFingerCount == 0 && currentFingerCount != 0) {
5908 mPointerGesture.resetTap();
5909 mPointerGesture.tapDownTime = when;
5910 mPointerGesture.tapX = x;
5911 mPointerGesture.tapY = y;
5912 }
5913 } else {
5914 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5915 // We need to provide feedback for each finger that goes down so we cannot wait
5916 // for the fingers to move before deciding what to do.
5917 //
5918 // The ambiguous case is deciding what to do when there are two fingers down but they
5919 // have not moved enough to determine whether they are part of a drag or part of a
5920 // freeform gesture, or just a press or long-press at the pointer location.
5921 //
5922 // When there are two fingers we start with the PRESS hypothesis and we generate a
5923 // down at the pointer location.
5924 //
5925 // When the two fingers move enough or when additional fingers are added, we make
5926 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5927 ALOG_ASSERT(activeTouchId >= 0);
5928
5929 bool settled = when >= mPointerGesture.firstTouchTime
5930 + mConfig.pointerGestureMultitouchSettleInterval;
5931 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5932 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5933 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5934 *outFinishPreviousGesture = true;
5935 } else if (!settled && currentFingerCount > lastFingerCount) {
5936 // Additional pointers have gone down but not yet settled.
5937 // Reset the gesture.
5938#if DEBUG_GESTURES
5939 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5940 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5941 + mConfig.pointerGestureMultitouchSettleInterval - when)
5942 * 0.000001f);
5943#endif
5944 *outCancelPreviousGesture = true;
5945 } else {
5946 // Continue previous gesture.
5947 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5948 }
5949
5950 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5951 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5952 mPointerGesture.activeGestureId = 0;
5953 mPointerGesture.referenceIdBits.clear();
5954 mPointerVelocityControl.reset();
5955
5956 // Use the centroid and pointer location as the reference points for the gesture.
5957#if DEBUG_GESTURES
5958 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5959 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5960 + mConfig.pointerGestureMultitouchSettleInterval - when)
5961 * 0.000001f);
5962#endif
Michael Wright842500e2015-03-13 17:32:02 -07005963 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005964 &mPointerGesture.referenceTouchX,
5965 &mPointerGesture.referenceTouchY);
5966 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5967 &mPointerGesture.referenceGestureY);
5968 }
5969
5970 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005971 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005972 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5973 uint32_t id = idBits.clearFirstMarkedBit();
5974 mPointerGesture.referenceDeltas[id].dx = 0;
5975 mPointerGesture.referenceDeltas[id].dy = 0;
5976 }
Michael Wright842500e2015-03-13 17:32:02 -07005977 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005978
5979 // Add delta for all fingers and calculate a common movement delta.
5980 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005981 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5982 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005983 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5984 bool first = (idBits == commonIdBits);
5985 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005986 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5987 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5989 delta.dx += cpd.x - lpd.x;
5990 delta.dy += cpd.y - lpd.y;
5991
5992 if (first) {
5993 commonDeltaX = delta.dx;
5994 commonDeltaY = delta.dy;
5995 } else {
5996 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5997 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5998 }
5999 }
6000
6001 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
6002 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
6003 float dist[MAX_POINTER_ID + 1];
6004 int32_t distOverThreshold = 0;
6005 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6006 uint32_t id = idBits.clearFirstMarkedBit();
6007 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6008 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
6009 delta.dy * mPointerYZoomScale);
6010 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
6011 distOverThreshold += 1;
6012 }
6013 }
6014
6015 // Only transition when at least two pointers have moved further than
6016 // the minimum distance threshold.
6017 if (distOverThreshold >= 2) {
6018 if (currentFingerCount > 2) {
6019 // There are more than two pointers, switch to FREEFORM.
6020#if DEBUG_GESTURES
6021 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
6022 currentFingerCount);
6023#endif
6024 *outCancelPreviousGesture = true;
6025 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6026 } else {
6027 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07006028 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006029 uint32_t id1 = idBits.clearFirstMarkedBit();
6030 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07006031 const RawPointerData::Pointer& p1 =
6032 mCurrentRawState.rawPointerData.pointerForId(id1);
6033 const RawPointerData::Pointer& p2 =
6034 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006035 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6036 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6037 // There are two pointers but they are too far apart for a SWIPE,
6038 // switch to FREEFORM.
6039#if DEBUG_GESTURES
6040 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6041 mutualDistance, mPointerGestureMaxSwipeWidth);
6042#endif
6043 *outCancelPreviousGesture = true;
6044 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6045 } else {
6046 // There are two pointers. Wait for both pointers to start moving
6047 // before deciding whether this is a SWIPE or FREEFORM gesture.
6048 float dist1 = dist[id1];
6049 float dist2 = dist[id2];
6050 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6051 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6052 // Calculate the dot product of the displacement vectors.
6053 // When the vectors are oriented in approximately the same direction,
6054 // the angle betweeen them is near zero and the cosine of the angle
6055 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6056 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6057 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6058 float dx1 = delta1.dx * mPointerXZoomScale;
6059 float dy1 = delta1.dy * mPointerYZoomScale;
6060 float dx2 = delta2.dx * mPointerXZoomScale;
6061 float dy2 = delta2.dy * mPointerYZoomScale;
6062 float dot = dx1 * dx2 + dy1 * dy2;
6063 float cosine = dot / (dist1 * dist2); // denominator always > 0
6064 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6065 // Pointers are moving in the same direction. Switch to SWIPE.
6066#if DEBUG_GESTURES
6067 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6068 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6069 "cosine %0.3f >= %0.3f",
6070 dist1, mConfig.pointerGestureMultitouchMinDistance,
6071 dist2, mConfig.pointerGestureMultitouchMinDistance,
6072 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6073#endif
6074 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6075 } else {
6076 // Pointers are moving in different directions. Switch to FREEFORM.
6077#if DEBUG_GESTURES
6078 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6079 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6080 "cosine %0.3f < %0.3f",
6081 dist1, mConfig.pointerGestureMultitouchMinDistance,
6082 dist2, mConfig.pointerGestureMultitouchMinDistance,
6083 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6084#endif
6085 *outCancelPreviousGesture = true;
6086 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6087 }
6088 }
6089 }
6090 }
6091 }
6092 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6093 // Switch from SWIPE to FREEFORM if additional pointers go down.
6094 // Cancel previous gesture.
6095 if (currentFingerCount > 2) {
6096#if DEBUG_GESTURES
6097 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6098 currentFingerCount);
6099#endif
6100 *outCancelPreviousGesture = true;
6101 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6102 }
6103 }
6104
6105 // Move the reference points based on the overall group motion of the fingers
6106 // except in PRESS mode while waiting for a transition to occur.
6107 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6108 && (commonDeltaX || commonDeltaY)) {
6109 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6110 uint32_t id = idBits.clearFirstMarkedBit();
6111 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6112 delta.dx = 0;
6113 delta.dy = 0;
6114 }
6115
6116 mPointerGesture.referenceTouchX += commonDeltaX;
6117 mPointerGesture.referenceTouchY += commonDeltaY;
6118
6119 commonDeltaX *= mPointerXMovementScale;
6120 commonDeltaY *= mPointerYMovementScale;
6121
6122 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6123 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6124
6125 mPointerGesture.referenceGestureX += commonDeltaX;
6126 mPointerGesture.referenceGestureY += commonDeltaY;
6127 }
6128
6129 // Report gestures.
6130 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6131 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6132 // PRESS or SWIPE mode.
6133#if DEBUG_GESTURES
6134 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6135 "activeGestureId=%d, currentTouchPointerCount=%d",
6136 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6137#endif
6138 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6139
6140 mPointerGesture.currentGestureIdBits.clear();
6141 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6142 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6143 mPointerGesture.currentGestureProperties[0].clear();
6144 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6145 mPointerGesture.currentGestureProperties[0].toolType =
6146 AMOTION_EVENT_TOOL_TYPE_FINGER;
6147 mPointerGesture.currentGestureCoords[0].clear();
6148 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6149 mPointerGesture.referenceGestureX);
6150 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6151 mPointerGesture.referenceGestureY);
6152 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6153 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6154 // FREEFORM mode.
6155#if DEBUG_GESTURES
6156 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6157 "activeGestureId=%d, currentTouchPointerCount=%d",
6158 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6159#endif
6160 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6161
6162 mPointerGesture.currentGestureIdBits.clear();
6163
6164 BitSet32 mappedTouchIdBits;
6165 BitSet32 usedGestureIdBits;
6166 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6167 // Initially, assign the active gesture id to the active touch point
6168 // if there is one. No other touch id bits are mapped yet.
6169 if (!*outCancelPreviousGesture) {
6170 mappedTouchIdBits.markBit(activeTouchId);
6171 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6172 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6173 mPointerGesture.activeGestureId;
6174 } else {
6175 mPointerGesture.activeGestureId = -1;
6176 }
6177 } else {
6178 // Otherwise, assume we mapped all touches from the previous frame.
6179 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006180 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6181 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6183
6184 // Check whether we need to choose a new active gesture id because the
6185 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006186 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6187 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006188 !upTouchIdBits.isEmpty(); ) {
6189 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6190 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6191 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6192 mPointerGesture.activeGestureId = -1;
6193 break;
6194 }
6195 }
6196 }
6197
6198#if DEBUG_GESTURES
6199 ALOGD("Gestures: FREEFORM follow up "
6200 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6201 "activeGestureId=%d",
6202 mappedTouchIdBits.value, usedGestureIdBits.value,
6203 mPointerGesture.activeGestureId);
6204#endif
6205
Michael Wright842500e2015-03-13 17:32:02 -07006206 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006207 for (uint32_t i = 0; i < currentFingerCount; i++) {
6208 uint32_t touchId = idBits.clearFirstMarkedBit();
6209 uint32_t gestureId;
6210 if (!mappedTouchIdBits.hasBit(touchId)) {
6211 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6212 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6213#if DEBUG_GESTURES
6214 ALOGD("Gestures: FREEFORM "
6215 "new mapping for touch id %d -> gesture id %d",
6216 touchId, gestureId);
6217#endif
6218 } else {
6219 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6220#if DEBUG_GESTURES
6221 ALOGD("Gestures: FREEFORM "
6222 "existing mapping for touch id %d -> gesture id %d",
6223 touchId, gestureId);
6224#endif
6225 }
6226 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6227 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6228
6229 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006230 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6232 * mPointerXZoomScale;
6233 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6234 * mPointerYZoomScale;
6235 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6236
6237 mPointerGesture.currentGestureProperties[i].clear();
6238 mPointerGesture.currentGestureProperties[i].id = gestureId;
6239 mPointerGesture.currentGestureProperties[i].toolType =
6240 AMOTION_EVENT_TOOL_TYPE_FINGER;
6241 mPointerGesture.currentGestureCoords[i].clear();
6242 mPointerGesture.currentGestureCoords[i].setAxisValue(
6243 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6244 mPointerGesture.currentGestureCoords[i].setAxisValue(
6245 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6246 mPointerGesture.currentGestureCoords[i].setAxisValue(
6247 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6248 }
6249
6250 if (mPointerGesture.activeGestureId < 0) {
6251 mPointerGesture.activeGestureId =
6252 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6253#if DEBUG_GESTURES
6254 ALOGD("Gestures: FREEFORM new "
6255 "activeGestureId=%d", mPointerGesture.activeGestureId);
6256#endif
6257 }
6258 }
6259 }
6260
Michael Wright842500e2015-03-13 17:32:02 -07006261 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262
6263#if DEBUG_GESTURES
6264 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6265 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6266 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6267 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6268 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6269 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6270 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6271 uint32_t id = idBits.clearFirstMarkedBit();
6272 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6273 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6274 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6275 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6276 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6277 id, index, properties.toolType,
6278 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6279 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6280 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6281 }
6282 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6283 uint32_t id = idBits.clearFirstMarkedBit();
6284 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6285 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6286 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6287 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6288 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6289 id, index, properties.toolType,
6290 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6291 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6292 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6293 }
6294#endif
6295 return true;
6296}
6297
6298void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6299 mPointerSimple.currentCoords.clear();
6300 mPointerSimple.currentProperties.clear();
6301
6302 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006303 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6304 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6305 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6306 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6307 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 mPointerController->setPosition(x, y);
6309
Michael Wright842500e2015-03-13 17:32:02 -07006310 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311 down = !hovering;
6312
6313 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006314 mPointerSimple.currentCoords.copyFrom(
6315 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006316 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6317 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6318 mPointerSimple.currentProperties.id = 0;
6319 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006320 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321 } else {
6322 down = false;
6323 hovering = false;
6324 }
6325
6326 dispatchPointerSimple(when, policyFlags, down, hovering);
6327}
6328
6329void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6330 abortPointerSimple(when, policyFlags);
6331}
6332
6333void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6334 mPointerSimple.currentCoords.clear();
6335 mPointerSimple.currentProperties.clear();
6336
6337 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006338 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6339 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6340 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006341 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006342 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6343 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006344 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006345 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006347 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006348 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 * mPointerYMovementScale;
6350
6351 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6352 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6353
6354 mPointerController->move(deltaX, deltaY);
6355 } else {
6356 mPointerVelocityControl.reset();
6357 }
6358
Michael Wright842500e2015-03-13 17:32:02 -07006359 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 hovering = !down;
6361
6362 float x, y;
6363 mPointerController->getPosition(&x, &y);
6364 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006365 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6367 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6368 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6369 hovering ? 0.0f : 1.0f);
6370 mPointerSimple.currentProperties.id = 0;
6371 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006372 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 } else {
6374 mPointerVelocityControl.reset();
6375
6376 down = false;
6377 hovering = false;
6378 }
6379
6380 dispatchPointerSimple(when, policyFlags, down, hovering);
6381}
6382
6383void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6384 abortPointerSimple(when, policyFlags);
6385
6386 mPointerVelocityControl.reset();
6387}
6388
6389void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6390 bool down, bool hovering) {
6391 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006392 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393
Yi Kong9b14ac62018-07-17 13:48:38 -07006394 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 if (down || hovering) {
6396 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6397 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006398 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6400 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6401 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6402 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006403 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 }
6405
6406 if (mPointerSimple.down && !down) {
6407 mPointerSimple.down = false;
6408
6409 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006410 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006411 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006412 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6413 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006414 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6415 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006416 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006417 getListener()->notifyMotion(&args);
6418 }
6419
6420 if (mPointerSimple.hovering && !hovering) {
6421 mPointerSimple.hovering = false;
6422
6423 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006424 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6425 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006426 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6427 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006428 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6429 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006430 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006431 getListener()->notifyMotion(&args);
6432 }
6433
6434 if (down) {
6435 if (!mPointerSimple.down) {
6436 mPointerSimple.down = true;
6437 mPointerSimple.downTime = when;
6438
6439 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006440 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6441 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006442 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6443 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006444 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006445 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6446 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006447 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006448 getListener()->notifyMotion(&args);
6449 }
6450
6451 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006452 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6453 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006454 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6455 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006456 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6457 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006458 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006459 getListener()->notifyMotion(&args);
6460 }
6461
6462 if (hovering) {
6463 if (!mPointerSimple.hovering) {
6464 mPointerSimple.hovering = true;
6465
6466 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006467 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6468 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006469 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006470 mCurrentRawState.buttonState, MotionClassification::NONE,
6471 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006472 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6473 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006474 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006475 getListener()->notifyMotion(&args);
6476 }
6477
6478 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006479 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6480 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006481 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006482 mCurrentRawState.buttonState, MotionClassification::NONE,
6483 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006484 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6485 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006486 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006487 getListener()->notifyMotion(&args);
6488 }
6489
Michael Wright842500e2015-03-13 17:32:02 -07006490 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6491 float vscroll = mCurrentRawState.rawVScroll;
6492 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006493 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6494 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006495
6496 // Send scroll.
6497 PointerCoords pointerCoords;
6498 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6499 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6500 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6501
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006502 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6503 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006504 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6505 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006506 1, &mPointerSimple.currentProperties, &pointerCoords,
6507 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006508 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006509 getListener()->notifyMotion(&args);
6510 }
6511
6512 // Save state.
6513 if (down || hovering) {
6514 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6515 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6516 } else {
6517 mPointerSimple.reset();
6518 }
6519}
6520
6521void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6522 mPointerSimple.currentCoords.clear();
6523 mPointerSimple.currentProperties.clear();
6524
6525 dispatchPointerSimple(when, policyFlags, false, false);
6526}
6527
6528void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006529 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006530 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006532 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6533 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534 PointerCoords pointerCoords[MAX_POINTERS];
6535 PointerProperties pointerProperties[MAX_POINTERS];
6536 uint32_t pointerCount = 0;
6537 while (!idBits.isEmpty()) {
6538 uint32_t id = idBits.clearFirstMarkedBit();
6539 uint32_t index = idToIndex[id];
6540 pointerProperties[pointerCount].copyFrom(properties[index]);
6541 pointerCoords[pointerCount].copyFrom(coords[index]);
6542
6543 if (changedId >= 0 && id == uint32_t(changedId)) {
6544 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6545 }
6546
6547 pointerCount += 1;
6548 }
6549
6550 ALOG_ASSERT(pointerCount != 0);
6551
6552 if (changedId >= 0 && pointerCount == 1) {
6553 // Replace initial down and final up action.
6554 // We can compare the action without masking off the changed pointer index
6555 // because we know the index is 0.
6556 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6557 action = AMOTION_EVENT_ACTION_DOWN;
6558 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6559 action = AMOTION_EVENT_ACTION_UP;
6560 } else {
6561 // Can't happen.
6562 ALOG_ASSERT(false);
6563 }
6564 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006565 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006566 const int32_t deviceId = getDeviceId();
6567 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006568 std::for_each(frames.begin(), frames.end(),
6569 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006570 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006571 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006572 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6573 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006574 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575 getListener()->notifyMotion(&args);
6576}
6577
6578bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6579 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6580 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6581 BitSet32 idBits) const {
6582 bool changed = false;
6583 while (!idBits.isEmpty()) {
6584 uint32_t id = idBits.clearFirstMarkedBit();
6585 uint32_t inIndex = inIdToIndex[id];
6586 uint32_t outIndex = outIdToIndex[id];
6587
6588 const PointerProperties& curInProperties = inProperties[inIndex];
6589 const PointerCoords& curInCoords = inCoords[inIndex];
6590 PointerProperties& curOutProperties = outProperties[outIndex];
6591 PointerCoords& curOutCoords = outCoords[outIndex];
6592
6593 if (curInProperties != curOutProperties) {
6594 curOutProperties.copyFrom(curInProperties);
6595 changed = true;
6596 }
6597
6598 if (curInCoords != curOutCoords) {
6599 curOutCoords.copyFrom(curInCoords);
6600 changed = true;
6601 }
6602 }
6603 return changed;
6604}
6605
6606void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006607 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6609 }
6610}
6611
Jeff Brownc9aa6282015-02-11 19:03:28 -08006612void TouchInputMapper::cancelTouch(nsecs_t when) {
6613 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006614 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006615}
6616
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006618 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006619 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006621 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6622 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6623 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006624}
6625
6626const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6627 int32_t x, int32_t y) {
6628 size_t numVirtualKeys = mVirtualKeys.size();
6629 for (size_t i = 0; i < numVirtualKeys; i++) {
6630 const VirtualKey& virtualKey = mVirtualKeys[i];
6631
6632#if DEBUG_VIRTUAL_KEYS
6633 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6634 "left=%d, top=%d, right=%d, bottom=%d",
6635 x, y,
6636 virtualKey.keyCode, virtualKey.scanCode,
6637 virtualKey.hitLeft, virtualKey.hitTop,
6638 virtualKey.hitRight, virtualKey.hitBottom);
6639#endif
6640
6641 if (virtualKey.isHit(x, y)) {
6642 return & virtualKey;
6643 }
6644 }
6645
Yi Kong9b14ac62018-07-17 13:48:38 -07006646 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006647}
6648
Michael Wright842500e2015-03-13 17:32:02 -07006649void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6650 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6651 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006652
Michael Wright842500e2015-03-13 17:32:02 -07006653 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006654
6655 if (currentPointerCount == 0) {
6656 // No pointers to assign.
6657 return;
6658 }
6659
6660 if (lastPointerCount == 0) {
6661 // All pointers are new.
6662 for (uint32_t i = 0; i < currentPointerCount; i++) {
6663 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006664 current->rawPointerData.pointers[i].id = id;
6665 current->rawPointerData.idToIndex[id] = i;
6666 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006667 }
6668 return;
6669 }
6670
6671 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006672 && current->rawPointerData.pointers[0].toolType
6673 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006674 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006675 uint32_t id = last->rawPointerData.pointers[0].id;
6676 current->rawPointerData.pointers[0].id = id;
6677 current->rawPointerData.idToIndex[id] = 0;
6678 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006679 return;
6680 }
6681
6682 // General case.
6683 // We build a heap of squared euclidean distances between current and last pointers
6684 // associated with the current and last pointer indices. Then, we find the best
6685 // match (by distance) for each current pointer.
6686 // The pointers must have the same tool type but it is possible for them to
6687 // transition from hovering to touching or vice-versa while retaining the same id.
6688 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6689
6690 uint32_t heapSize = 0;
6691 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6692 currentPointerIndex++) {
6693 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6694 lastPointerIndex++) {
6695 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006696 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006697 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006698 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006699 if (currentPointer.toolType == lastPointer.toolType) {
6700 int64_t deltaX = currentPointer.x - lastPointer.x;
6701 int64_t deltaY = currentPointer.y - lastPointer.y;
6702
6703 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6704
6705 // Insert new element into the heap (sift up).
6706 heap[heapSize].currentPointerIndex = currentPointerIndex;
6707 heap[heapSize].lastPointerIndex = lastPointerIndex;
6708 heap[heapSize].distance = distance;
6709 heapSize += 1;
6710 }
6711 }
6712 }
6713
6714 // Heapify
6715 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6716 startIndex -= 1;
6717 for (uint32_t parentIndex = startIndex; ;) {
6718 uint32_t childIndex = parentIndex * 2 + 1;
6719 if (childIndex >= heapSize) {
6720 break;
6721 }
6722
6723 if (childIndex + 1 < heapSize
6724 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6725 childIndex += 1;
6726 }
6727
6728 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6729 break;
6730 }
6731
6732 swap(heap[parentIndex], heap[childIndex]);
6733 parentIndex = childIndex;
6734 }
6735 }
6736
6737#if DEBUG_POINTER_ASSIGNMENT
6738 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6739 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006740 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006741 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6742 heap[i].distance);
6743 }
6744#endif
6745
6746 // Pull matches out by increasing order of distance.
6747 // To avoid reassigning pointers that have already been matched, the loop keeps track
6748 // of which last and current pointers have been matched using the matchedXXXBits variables.
6749 // It also tracks the used pointer id bits.
6750 BitSet32 matchedLastBits(0);
6751 BitSet32 matchedCurrentBits(0);
6752 BitSet32 usedIdBits(0);
6753 bool first = true;
6754 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6755 while (heapSize > 0) {
6756 if (first) {
6757 // The first time through the loop, we just consume the root element of
6758 // the heap (the one with smallest distance).
6759 first = false;
6760 } else {
6761 // Previous iterations consumed the root element of the heap.
6762 // Pop root element off of the heap (sift down).
6763 heap[0] = heap[heapSize];
6764 for (uint32_t parentIndex = 0; ;) {
6765 uint32_t childIndex = parentIndex * 2 + 1;
6766 if (childIndex >= heapSize) {
6767 break;
6768 }
6769
6770 if (childIndex + 1 < heapSize
6771 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6772 childIndex += 1;
6773 }
6774
6775 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6776 break;
6777 }
6778
6779 swap(heap[parentIndex], heap[childIndex]);
6780 parentIndex = childIndex;
6781 }
6782
6783#if DEBUG_POINTER_ASSIGNMENT
6784 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6785 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006786 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006787 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6788 heap[i].distance);
6789 }
6790#endif
6791 }
6792
6793 heapSize -= 1;
6794
6795 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6796 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6797
6798 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6799 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6800
6801 matchedCurrentBits.markBit(currentPointerIndex);
6802 matchedLastBits.markBit(lastPointerIndex);
6803
Michael Wright842500e2015-03-13 17:32:02 -07006804 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6805 current->rawPointerData.pointers[currentPointerIndex].id = id;
6806 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6807 current->rawPointerData.markIdBit(id,
6808 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006809 usedIdBits.markBit(id);
6810
6811#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006812 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6813 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006814 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6815#endif
6816 break;
6817 }
6818 }
6819
6820 // Assign fresh ids to pointers that were not matched in the process.
6821 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6822 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6823 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6824
Michael Wright842500e2015-03-13 17:32:02 -07006825 current->rawPointerData.pointers[currentPointerIndex].id = id;
6826 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6827 current->rawPointerData.markIdBit(id,
6828 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006829
6830#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006831 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006832#endif
6833 }
6834}
6835
6836int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6837 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6838 return AKEY_STATE_VIRTUAL;
6839 }
6840
6841 size_t numVirtualKeys = mVirtualKeys.size();
6842 for (size_t i = 0; i < numVirtualKeys; i++) {
6843 const VirtualKey& virtualKey = mVirtualKeys[i];
6844 if (virtualKey.keyCode == keyCode) {
6845 return AKEY_STATE_UP;
6846 }
6847 }
6848
6849 return AKEY_STATE_UNKNOWN;
6850}
6851
6852int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6853 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6854 return AKEY_STATE_VIRTUAL;
6855 }
6856
6857 size_t numVirtualKeys = mVirtualKeys.size();
6858 for (size_t i = 0; i < numVirtualKeys; i++) {
6859 const VirtualKey& virtualKey = mVirtualKeys[i];
6860 if (virtualKey.scanCode == scanCode) {
6861 return AKEY_STATE_UP;
6862 }
6863 }
6864
6865 return AKEY_STATE_UNKNOWN;
6866}
6867
6868bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6869 const int32_t* keyCodes, uint8_t* outFlags) {
6870 size_t numVirtualKeys = mVirtualKeys.size();
6871 for (size_t i = 0; i < numVirtualKeys; i++) {
6872 const VirtualKey& virtualKey = mVirtualKeys[i];
6873
6874 for (size_t i = 0; i < numCodes; i++) {
6875 if (virtualKey.keyCode == keyCodes[i]) {
6876 outFlags[i] = 1;
6877 }
6878 }
6879 }
6880
6881 return true;
6882}
6883
Arthur Hungc23540e2018-11-29 20:42:11 +08006884std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6885 if (mParameters.hasAssociatedDisplay) {
6886 if (mDeviceMode == DEVICE_MODE_POINTER) {
6887 return std::make_optional(mPointerController->getDisplayId());
6888 } else {
6889 return std::make_optional(mViewport.displayId);
6890 }
6891 }
6892 return std::nullopt;
6893}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006894
6895// --- SingleTouchInputMapper ---
6896
6897SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6898 TouchInputMapper(device) {
6899}
6900
6901SingleTouchInputMapper::~SingleTouchInputMapper() {
6902}
6903
6904void SingleTouchInputMapper::reset(nsecs_t when) {
6905 mSingleTouchMotionAccumulator.reset(getDevice());
6906
6907 TouchInputMapper::reset(when);
6908}
6909
6910void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6911 TouchInputMapper::process(rawEvent);
6912
6913 mSingleTouchMotionAccumulator.process(rawEvent);
6914}
6915
Michael Wright842500e2015-03-13 17:32:02 -07006916void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006917 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006918 outState->rawPointerData.pointerCount = 1;
6919 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006920
6921 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6922 && (mTouchButtonAccumulator.isHovering()
6923 || (mRawPointerAxes.pressure.valid
6924 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006925 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006926
Michael Wright842500e2015-03-13 17:32:02 -07006927 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006928 outPointer.id = 0;
6929 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6930 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6931 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6932 outPointer.touchMajor = 0;
6933 outPointer.touchMinor = 0;
6934 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6935 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6936 outPointer.orientation = 0;
6937 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6938 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6939 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6940 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6941 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6942 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6943 }
6944 outPointer.isHovering = isHovering;
6945 }
6946}
6947
6948void SingleTouchInputMapper::configureRawPointerAxes() {
6949 TouchInputMapper::configureRawPointerAxes();
6950
6951 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6952 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6953 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6954 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6955 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6956 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6957 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6958}
6959
6960bool SingleTouchInputMapper::hasStylus() const {
6961 return mTouchButtonAccumulator.hasStylus();
6962}
6963
6964
6965// --- MultiTouchInputMapper ---
6966
6967MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6968 TouchInputMapper(device) {
6969}
6970
6971MultiTouchInputMapper::~MultiTouchInputMapper() {
6972}
6973
6974void MultiTouchInputMapper::reset(nsecs_t when) {
6975 mMultiTouchMotionAccumulator.reset(getDevice());
6976
6977 mPointerIdBits.clear();
6978
6979 TouchInputMapper::reset(when);
6980}
6981
6982void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6983 TouchInputMapper::process(rawEvent);
6984
6985 mMultiTouchMotionAccumulator.process(rawEvent);
6986}
6987
Michael Wright842500e2015-03-13 17:32:02 -07006988void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006989 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6990 size_t outCount = 0;
6991 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006992 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006993
6994 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6995 const MultiTouchMotionAccumulator::Slot* inSlot =
6996 mMultiTouchMotionAccumulator.getSlot(inIndex);
6997 if (!inSlot->isInUse()) {
6998 continue;
6999 }
7000
7001 if (outCount >= MAX_POINTERS) {
7002#if DEBUG_POINTERS
7003 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
7004 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007005 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007006#endif
7007 break; // too many fingers!
7008 }
7009
Michael Wright842500e2015-03-13 17:32:02 -07007010 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08007011 outPointer.x = inSlot->getX();
7012 outPointer.y = inSlot->getY();
7013 outPointer.pressure = inSlot->getPressure();
7014 outPointer.touchMajor = inSlot->getTouchMajor();
7015 outPointer.touchMinor = inSlot->getTouchMinor();
7016 outPointer.toolMajor = inSlot->getToolMajor();
7017 outPointer.toolMinor = inSlot->getToolMinor();
7018 outPointer.orientation = inSlot->getOrientation();
7019 outPointer.distance = inSlot->getDistance();
7020 outPointer.tiltX = 0;
7021 outPointer.tiltY = 0;
7022
7023 outPointer.toolType = inSlot->getToolType();
7024 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7025 outPointer.toolType = mTouchButtonAccumulator.getToolType();
7026 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7027 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
7028 }
7029 }
7030
7031 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
7032 && (mTouchButtonAccumulator.isHovering()
7033 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
7034 outPointer.isHovering = isHovering;
7035
7036 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08007037 if (mHavePointerIds) {
7038 int32_t trackingId = inSlot->getTrackingId();
7039 int32_t id = -1;
7040 if (trackingId >= 0) {
7041 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7042 uint32_t n = idBits.clearFirstMarkedBit();
7043 if (mPointerTrackingIdMap[n] == trackingId) {
7044 id = n;
7045 }
7046 }
7047
7048 if (id < 0 && !mPointerIdBits.isFull()) {
7049 id = mPointerIdBits.markFirstUnmarkedBit();
7050 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007051 }
Michael Wright842500e2015-03-13 17:32:02 -07007052 }
gaoshang1a632de2016-08-24 10:23:50 +08007053 if (id < 0) {
7054 mHavePointerIds = false;
7055 outState->rawPointerData.clearIdBits();
7056 newPointerIdBits.clear();
7057 } else {
7058 outPointer.id = id;
7059 outState->rawPointerData.idToIndex[id] = outCount;
7060 outState->rawPointerData.markIdBit(id, isHovering);
7061 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007062 }
Michael Wright842500e2015-03-13 17:32:02 -07007063 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007064 outCount += 1;
7065 }
7066
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007067 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007068 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007069 mPointerIdBits = newPointerIdBits;
7070
7071 mMultiTouchMotionAccumulator.finishSync();
7072}
7073
7074void MultiTouchInputMapper::configureRawPointerAxes() {
7075 TouchInputMapper::configureRawPointerAxes();
7076
7077 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7078 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7079 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7080 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7081 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7082 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7083 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7084 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7085 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7086 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7087 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7088
7089 if (mRawPointerAxes.trackingId.valid
7090 && mRawPointerAxes.slot.valid
7091 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7092 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7093 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007094 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7095 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007096 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007097 slotCount = MAX_SLOTS;
7098 }
7099 mMultiTouchMotionAccumulator.configure(getDevice(),
7100 slotCount, true /*usingSlotsProtocol*/);
7101 } else {
7102 mMultiTouchMotionAccumulator.configure(getDevice(),
7103 MAX_POINTERS, false /*usingSlotsProtocol*/);
7104 }
7105}
7106
7107bool MultiTouchInputMapper::hasStylus() const {
7108 return mMultiTouchMotionAccumulator.hasStylus()
7109 || mTouchButtonAccumulator.hasStylus();
7110}
7111
Michael Wright842500e2015-03-13 17:32:02 -07007112// --- ExternalStylusInputMapper
7113
7114ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7115 InputMapper(device) {
7116
7117}
7118
7119uint32_t ExternalStylusInputMapper::getSources() {
7120 return AINPUT_SOURCE_STYLUS;
7121}
7122
7123void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7124 InputMapper::populateDeviceInfo(info);
7125 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7126 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7127}
7128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007129void ExternalStylusInputMapper::dump(std::string& dump) {
7130 dump += INDENT2 "External Stylus Input Mapper:\n";
7131 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007132 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007133 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007134 dumpStylusState(dump, mStylusState);
7135}
7136
7137void ExternalStylusInputMapper::configure(nsecs_t when,
7138 const InputReaderConfiguration* config, uint32_t changes) {
7139 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7140 mTouchButtonAccumulator.configure(getDevice());
7141}
7142
7143void ExternalStylusInputMapper::reset(nsecs_t when) {
7144 InputDevice* device = getDevice();
7145 mSingleTouchMotionAccumulator.reset(device);
7146 mTouchButtonAccumulator.reset(device);
7147 InputMapper::reset(when);
7148}
7149
7150void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7151 mSingleTouchMotionAccumulator.process(rawEvent);
7152 mTouchButtonAccumulator.process(rawEvent);
7153
7154 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7155 sync(rawEvent->when);
7156 }
7157}
7158
7159void ExternalStylusInputMapper::sync(nsecs_t when) {
7160 mStylusState.clear();
7161
7162 mStylusState.when = when;
7163
Michael Wright45ccacf2015-04-21 19:01:58 +01007164 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7165 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7166 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7167 }
7168
Michael Wright842500e2015-03-13 17:32:02 -07007169 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7170 if (mRawPressureAxis.valid) {
7171 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7172 } else if (mTouchButtonAccumulator.isToolActive()) {
7173 mStylusState.pressure = 1.0f;
7174 } else {
7175 mStylusState.pressure = 0.0f;
7176 }
7177
7178 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007179
7180 mContext->dispatchExternalStylusState(mStylusState);
7181}
7182
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183
7184// --- JoystickInputMapper ---
7185
7186JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7187 InputMapper(device) {
7188}
7189
7190JoystickInputMapper::~JoystickInputMapper() {
7191}
7192
7193uint32_t JoystickInputMapper::getSources() {
7194 return AINPUT_SOURCE_JOYSTICK;
7195}
7196
7197void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7198 InputMapper::populateDeviceInfo(info);
7199
7200 for (size_t i = 0; i < mAxes.size(); i++) {
7201 const Axis& axis = mAxes.valueAt(i);
7202 addMotionRange(axis.axisInfo.axis, axis, info);
7203
7204 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7205 addMotionRange(axis.axisInfo.highAxis, axis, info);
7206
7207 }
7208 }
7209}
7210
7211void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7212 InputDeviceInfo* info) {
7213 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7214 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7215 /* In order to ease the transition for developers from using the old axes
7216 * to the newer, more semantically correct axes, we'll continue to register
7217 * the old axes as duplicates of their corresponding new ones. */
7218 int32_t compatAxis = getCompatAxis(axisId);
7219 if (compatAxis >= 0) {
7220 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7221 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7222 }
7223}
7224
7225/* A mapping from axes the joystick actually has to the axes that should be
7226 * artificially created for compatibility purposes.
7227 * Returns -1 if no compatibility axis is needed. */
7228int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7229 switch(axis) {
7230 case AMOTION_EVENT_AXIS_LTRIGGER:
7231 return AMOTION_EVENT_AXIS_BRAKE;
7232 case AMOTION_EVENT_AXIS_RTRIGGER:
7233 return AMOTION_EVENT_AXIS_GAS;
7234 }
7235 return -1;
7236}
7237
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007238void JoystickInputMapper::dump(std::string& dump) {
7239 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007240
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007241 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007242 size_t numAxes = mAxes.size();
7243 for (size_t i = 0; i < numAxes; i++) {
7244 const Axis& axis = mAxes.valueAt(i);
7245 const char* label = getAxisLabel(axis.axisInfo.axis);
7246 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007247 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007248 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007249 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007250 }
7251 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7252 label = getAxisLabel(axis.axisInfo.highAxis);
7253 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007254 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007255 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007256 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007257 axis.axisInfo.splitValue);
7258 }
7259 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007260 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007261 }
7262
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007263 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 -08007264 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007265 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007266 "highScale=%0.5f, highOffset=%0.5f\n",
7267 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007268 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007269 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7270 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7271 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7272 }
7273}
7274
7275void JoystickInputMapper::configure(nsecs_t when,
7276 const InputReaderConfiguration* config, uint32_t changes) {
7277 InputMapper::configure(when, config, changes);
7278
7279 if (!changes) { // first time only
7280 // Collect all axes.
7281 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7282 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7283 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7284 continue; // axis must be claimed by a different device
7285 }
7286
7287 RawAbsoluteAxisInfo rawAxisInfo;
7288 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7289 if (rawAxisInfo.valid) {
7290 // Map axis.
7291 AxisInfo axisInfo;
7292 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7293 if (!explicitlyMapped) {
7294 // Axis is not explicitly mapped, will choose a generic axis later.
7295 axisInfo.mode = AxisInfo::MODE_NORMAL;
7296 axisInfo.axis = -1;
7297 }
7298
7299 // Apply flat override.
7300 int32_t rawFlat = axisInfo.flatOverride < 0
7301 ? rawAxisInfo.flat : axisInfo.flatOverride;
7302
7303 // Calculate scaling factors and limits.
7304 Axis axis;
7305 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7306 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7307 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7308 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7309 scale, 0.0f, highScale, 0.0f,
7310 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7311 rawAxisInfo.resolution * scale);
7312 } else if (isCenteredAxis(axisInfo.axis)) {
7313 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7314 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7315 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7316 scale, offset, scale, offset,
7317 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7318 rawAxisInfo.resolution * scale);
7319 } else {
7320 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7321 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7322 scale, 0.0f, scale, 0.0f,
7323 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7324 rawAxisInfo.resolution * scale);
7325 }
7326
7327 // To eliminate noise while the joystick is at rest, filter out small variations
7328 // in axis values up front.
7329 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7330
7331 mAxes.add(abs, axis);
7332 }
7333 }
7334
7335 // If there are too many axes, start dropping them.
7336 // Prefer to keep explicitly mapped axes.
7337 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007338 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007339 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007340 pruneAxes(true);
7341 pruneAxes(false);
7342 }
7343
7344 // Assign generic axis ids to remaining axes.
7345 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7346 size_t numAxes = mAxes.size();
7347 for (size_t i = 0; i < numAxes; i++) {
7348 Axis& axis = mAxes.editValueAt(i);
7349 if (axis.axisInfo.axis < 0) {
7350 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7351 && haveAxis(nextGenericAxisId)) {
7352 nextGenericAxisId += 1;
7353 }
7354
7355 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7356 axis.axisInfo.axis = nextGenericAxisId;
7357 nextGenericAxisId += 1;
7358 } else {
7359 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7360 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007361 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007362 mAxes.removeItemsAt(i--);
7363 numAxes -= 1;
7364 }
7365 }
7366 }
7367 }
7368}
7369
7370bool JoystickInputMapper::haveAxis(int32_t axisId) {
7371 size_t numAxes = mAxes.size();
7372 for (size_t i = 0; i < numAxes; i++) {
7373 const Axis& axis = mAxes.valueAt(i);
7374 if (axis.axisInfo.axis == axisId
7375 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7376 && axis.axisInfo.highAxis == axisId)) {
7377 return true;
7378 }
7379 }
7380 return false;
7381}
7382
7383void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7384 size_t i = mAxes.size();
7385 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7386 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7387 continue;
7388 }
7389 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007390 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007391 mAxes.removeItemsAt(i);
7392 }
7393}
7394
7395bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7396 switch (axis) {
7397 case AMOTION_EVENT_AXIS_X:
7398 case AMOTION_EVENT_AXIS_Y:
7399 case AMOTION_EVENT_AXIS_Z:
7400 case AMOTION_EVENT_AXIS_RX:
7401 case AMOTION_EVENT_AXIS_RY:
7402 case AMOTION_EVENT_AXIS_RZ:
7403 case AMOTION_EVENT_AXIS_HAT_X:
7404 case AMOTION_EVENT_AXIS_HAT_Y:
7405 case AMOTION_EVENT_AXIS_ORIENTATION:
7406 case AMOTION_EVENT_AXIS_RUDDER:
7407 case AMOTION_EVENT_AXIS_WHEEL:
7408 return true;
7409 default:
7410 return false;
7411 }
7412}
7413
7414void JoystickInputMapper::reset(nsecs_t when) {
7415 // Recenter all axes.
7416 size_t numAxes = mAxes.size();
7417 for (size_t i = 0; i < numAxes; i++) {
7418 Axis& axis = mAxes.editValueAt(i);
7419 axis.resetValue();
7420 }
7421
7422 InputMapper::reset(when);
7423}
7424
7425void JoystickInputMapper::process(const RawEvent* rawEvent) {
7426 switch (rawEvent->type) {
7427 case EV_ABS: {
7428 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7429 if (index >= 0) {
7430 Axis& axis = mAxes.editValueAt(index);
7431 float newValue, highNewValue;
7432 switch (axis.axisInfo.mode) {
7433 case AxisInfo::MODE_INVERT:
7434 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7435 * axis.scale + axis.offset;
7436 highNewValue = 0.0f;
7437 break;
7438 case AxisInfo::MODE_SPLIT:
7439 if (rawEvent->value < axis.axisInfo.splitValue) {
7440 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7441 * axis.scale + axis.offset;
7442 highNewValue = 0.0f;
7443 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7444 newValue = 0.0f;
7445 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7446 * axis.highScale + axis.highOffset;
7447 } else {
7448 newValue = 0.0f;
7449 highNewValue = 0.0f;
7450 }
7451 break;
7452 default:
7453 newValue = rawEvent->value * axis.scale + axis.offset;
7454 highNewValue = 0.0f;
7455 break;
7456 }
7457 axis.newValue = newValue;
7458 axis.highNewValue = highNewValue;
7459 }
7460 break;
7461 }
7462
7463 case EV_SYN:
7464 switch (rawEvent->code) {
7465 case SYN_REPORT:
7466 sync(rawEvent->when, false /*force*/);
7467 break;
7468 }
7469 break;
7470 }
7471}
7472
7473void JoystickInputMapper::sync(nsecs_t when, bool force) {
7474 if (!filterAxes(force)) {
7475 return;
7476 }
7477
7478 int32_t metaState = mContext->getGlobalMetaState();
7479 int32_t buttonState = 0;
7480
7481 PointerProperties pointerProperties;
7482 pointerProperties.clear();
7483 pointerProperties.id = 0;
7484 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7485
7486 PointerCoords pointerCoords;
7487 pointerCoords.clear();
7488
7489 size_t numAxes = mAxes.size();
7490 for (size_t i = 0; i < numAxes; i++) {
7491 const Axis& axis = mAxes.valueAt(i);
7492 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7493 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7494 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7495 axis.highCurrentValue);
7496 }
7497 }
7498
7499 // Moving a joystick axis should not wake the device because joysticks can
7500 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7501 // button will likely wake the device.
7502 // TODO: Use the input device configuration to control this behavior more finely.
7503 uint32_t policyFlags = 0;
7504
Prabir Pradhan42611e02018-11-27 14:04:02 -08007505 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7506 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007507 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7508 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7509 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007510 getListener()->notifyMotion(&args);
7511}
7512
7513void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7514 int32_t axis, float value) {
7515 pointerCoords->setAxisValue(axis, value);
7516 /* In order to ease the transition for developers from using the old axes
7517 * to the newer, more semantically correct axes, we'll continue to produce
7518 * values for the old axes as mirrors of the value of their corresponding
7519 * new axes. */
7520 int32_t compatAxis = getCompatAxis(axis);
7521 if (compatAxis >= 0) {
7522 pointerCoords->setAxisValue(compatAxis, value);
7523 }
7524}
7525
7526bool JoystickInputMapper::filterAxes(bool force) {
7527 bool atLeastOneSignificantChange = force;
7528 size_t numAxes = mAxes.size();
7529 for (size_t i = 0; i < numAxes; i++) {
7530 Axis& axis = mAxes.editValueAt(i);
7531 if (force || hasValueChangedSignificantly(axis.filter,
7532 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7533 axis.currentValue = axis.newValue;
7534 atLeastOneSignificantChange = true;
7535 }
7536 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7537 if (force || hasValueChangedSignificantly(axis.filter,
7538 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7539 axis.highCurrentValue = axis.highNewValue;
7540 atLeastOneSignificantChange = true;
7541 }
7542 }
7543 }
7544 return atLeastOneSignificantChange;
7545}
7546
7547bool JoystickInputMapper::hasValueChangedSignificantly(
7548 float filter, float newValue, float currentValue, float min, float max) {
7549 if (newValue != currentValue) {
7550 // Filter out small changes in value unless the value is converging on the axis
7551 // bounds or center point. This is intended to reduce the amount of information
7552 // sent to applications by particularly noisy joysticks (such as PS3).
7553 if (fabs(newValue - currentValue) > filter
7554 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7555 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7556 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7557 return true;
7558 }
7559 }
7560 return false;
7561}
7562
7563bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7564 float filter, float newValue, float currentValue, float thresholdValue) {
7565 float newDistance = fabs(newValue - thresholdValue);
7566 if (newDistance < filter) {
7567 float oldDistance = fabs(currentValue - thresholdValue);
7568 if (newDistance < oldDistance) {
7569 return true;
7570 }
7571 }
7572 return false;
7573}
7574
7575} // namespace android