blob: f84aa34a5c2c085a56b2768df5e6fc1b8d8c818f [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,
4553 mCurrentCookedState.cookedPointerData.touchingIdBits);
4554 }
4555
Michael Wright8e812822015-06-22 16:18:21 +01004556 if (!mCurrentMotionAborted) {
4557 dispatchButtonRelease(when, policyFlags);
4558 dispatchHoverExit(when, policyFlags);
4559 dispatchTouches(when, policyFlags);
4560 dispatchHoverEnterAndMove(when, policyFlags);
4561 dispatchButtonPress(when, policyFlags);
4562 }
4563
4564 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4565 mCurrentMotionAborted = false;
4566 }
Michael Wright842500e2015-03-13 17:32:02 -07004567 }
4568
4569 // Synthesize key up from raw buttons if needed.
4570 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004571 mViewport.displayId, policyFlags,
4572 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004573
4574 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004575 mCurrentRawState.rawVScroll = 0;
4576 mCurrentRawState.rawHScroll = 0;
4577
4578 // Copy current touch to last touch in preparation for the next cycle.
4579 mLastRawState.copyFrom(mCurrentRawState);
4580 mLastCookedState.copyFrom(mCurrentCookedState);
4581}
4582
4583void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004584 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004585 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4586 }
4587}
4588
4589void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004590 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4591 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004592
Michael Wright53dca3a2015-04-23 17:39:53 +01004593 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4594 float pressure = mExternalStylusState.pressure;
4595 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4596 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4597 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4598 }
4599 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4600 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4601
4602 PointerProperties& properties =
4603 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004604 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4605 properties.toolType = mExternalStylusState.toolType;
4606 }
4607 }
4608}
4609
4610bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4611 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4612 return false;
4613 }
4614
4615 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4616 && state.rawPointerData.pointerCount != 0;
4617 if (initialDown) {
4618 if (mExternalStylusState.pressure != 0.0f) {
4619#if DEBUG_STYLUS_FUSION
4620 ALOGD("Have both stylus and touch data, beginning fusion");
4621#endif
4622 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4623 } else if (timeout) {
4624#if DEBUG_STYLUS_FUSION
4625 ALOGD("Timeout expired, assuming touch is not a stylus.");
4626#endif
4627 resetExternalStylus();
4628 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004629 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4630 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004631 }
4632#if DEBUG_STYLUS_FUSION
4633 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004634 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004635#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004636 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004637 return true;
4638 }
4639 }
4640
4641 // Check if the stylus pointer has gone up.
4642 if (mExternalStylusId != -1 &&
4643 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4644#if DEBUG_STYLUS_FUSION
4645 ALOGD("Stylus pointer is going up");
4646#endif
4647 mExternalStylusId = -1;
4648 }
4649
4650 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004651}
4652
4653void TouchInputMapper::timeoutExpired(nsecs_t when) {
4654 if (mDeviceMode == DEVICE_MODE_POINTER) {
4655 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4656 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4657 }
Michael Wright842500e2015-03-13 17:32:02 -07004658 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004659 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004660 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004661 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4662 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004663 }
4664 }
4665}
4666
4667void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004668 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004669 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004670 // We're either in the middle of a fused stream of data or we're waiting on data before
4671 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4672 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004673 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004674 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004675 }
4676}
4677
4678bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4679 // Check for release of a virtual key.
4680 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004681 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004682 // Pointer went up while virtual key was down.
4683 mCurrentVirtualKey.down = false;
4684 if (!mCurrentVirtualKey.ignored) {
4685#if DEBUG_VIRTUAL_KEYS
4686 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4687 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4688#endif
4689 dispatchVirtualKey(when, policyFlags,
4690 AKEY_EVENT_ACTION_UP,
4691 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4692 }
4693 return true;
4694 }
4695
Michael Wright842500e2015-03-13 17:32:02 -07004696 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4697 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4698 const RawPointerData::Pointer& pointer =
4699 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4701 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4702 // Pointer is still within the space of the virtual key.
4703 return true;
4704 }
4705 }
4706
4707 // Pointer left virtual key area or another pointer also went down.
4708 // Send key cancellation but do not consume the touch yet.
4709 // This is useful when the user swipes through from the virtual key area
4710 // into the main display surface.
4711 mCurrentVirtualKey.down = false;
4712 if (!mCurrentVirtualKey.ignored) {
4713#if DEBUG_VIRTUAL_KEYS
4714 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4715 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4716#endif
4717 dispatchVirtualKey(when, policyFlags,
4718 AKEY_EVENT_ACTION_UP,
4719 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4720 | AKEY_EVENT_FLAG_CANCELED);
4721 }
4722 }
4723
Michael Wright842500e2015-03-13 17:32:02 -07004724 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4725 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004727 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4728 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004729 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4730 // If exactly one pointer went down, check for virtual key hit.
4731 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004732 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4734 if (virtualKey) {
4735 mCurrentVirtualKey.down = true;
4736 mCurrentVirtualKey.downTime = when;
4737 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4738 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4739 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4740 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4741
4742 if (!mCurrentVirtualKey.ignored) {
4743#if DEBUG_VIRTUAL_KEYS
4744 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4745 mCurrentVirtualKey.keyCode,
4746 mCurrentVirtualKey.scanCode);
4747#endif
4748 dispatchVirtualKey(when, policyFlags,
4749 AKEY_EVENT_ACTION_DOWN,
4750 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4751 }
4752 }
4753 }
4754 return true;
4755 }
4756 }
4757
4758 // Disable all virtual key touches that happen within a short time interval of the
4759 // most recent touch within the screen area. The idea is to filter out stray
4760 // virtual key presses when interacting with the touch screen.
4761 //
4762 // Problems we're trying to solve:
4763 //
4764 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4765 // virtual key area that is implemented by a separate touch panel and accidentally
4766 // triggers a virtual key.
4767 //
4768 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4769 // area and accidentally triggers a virtual key. This often happens when virtual keys
4770 // are layed out below the screen near to where the on screen keyboard's space bar
4771 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004772 if (mConfig.virtualKeyQuietTime > 0 &&
4773 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4775 }
4776 return false;
4777}
4778
4779void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4780 int32_t keyEventAction, int32_t keyEventFlags) {
4781 int32_t keyCode = mCurrentVirtualKey.keyCode;
4782 int32_t scanCode = mCurrentVirtualKey.scanCode;
4783 nsecs_t downTime = mCurrentVirtualKey.downTime;
4784 int32_t metaState = mContext->getGlobalMetaState();
4785 policyFlags |= POLICY_FLAG_VIRTUAL;
4786
Prabir Pradhan42611e02018-11-27 14:04:02 -08004787 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4788 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004789 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790 getListener()->notifyKey(&args);
4791}
4792
Michael Wright8e812822015-06-22 16:18:21 +01004793void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4794 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4795 if (!currentIdBits.isEmpty()) {
4796 int32_t metaState = getContext()->getGlobalMetaState();
4797 int32_t buttonState = mCurrentCookedState.buttonState;
4798 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4799 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004800 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004801 mCurrentCookedState.cookedPointerData.pointerProperties,
4802 mCurrentCookedState.cookedPointerData.pointerCoords,
4803 mCurrentCookedState.cookedPointerData.idToIndex,
4804 currentIdBits, -1,
4805 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4806 mCurrentMotionAborted = true;
4807 }
4808}
4809
Michael Wrightd02c5b62014-02-10 15:10:22 -08004810void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004811 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4812 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004814 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815
4816 if (currentIdBits == lastIdBits) {
4817 if (!currentIdBits.isEmpty()) {
4818 // No pointer id changes so this is a move event.
4819 // The listener takes care of batching moves so we don't have to deal with that here.
4820 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004821 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004823 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004824 mCurrentCookedState.cookedPointerData.pointerProperties,
4825 mCurrentCookedState.cookedPointerData.pointerCoords,
4826 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004827 currentIdBits, -1,
4828 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4829 }
4830 } else {
4831 // There may be pointers going up and pointers going down and pointers moving
4832 // all at the same time.
4833 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4834 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4835 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4836 BitSet32 dispatchedIdBits(lastIdBits.value);
4837
4838 // Update last coordinates of pointers that have moved so that we observe the new
4839 // pointer positions at the same time as other pointers that have just gone up.
4840 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004841 mCurrentCookedState.cookedPointerData.pointerProperties,
4842 mCurrentCookedState.cookedPointerData.pointerCoords,
4843 mCurrentCookedState.cookedPointerData.idToIndex,
4844 mLastCookedState.cookedPointerData.pointerProperties,
4845 mLastCookedState.cookedPointerData.pointerCoords,
4846 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004848 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 moveNeeded = true;
4850 }
4851
4852 // Dispatch pointer up events.
4853 while (!upIdBits.isEmpty()) {
4854 uint32_t upId = upIdBits.clearFirstMarkedBit();
4855
4856 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004857 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004858 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004859 mLastCookedState.cookedPointerData.pointerProperties,
4860 mLastCookedState.cookedPointerData.pointerCoords,
4861 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004862 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 dispatchedIdBits.clearBit(upId);
4864 }
4865
4866 // Dispatch move events if any of the remaining pointers moved from their old locations.
4867 // Although applications receive new locations as part of individual pointer up
4868 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004869 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004870 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4871 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004872 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004873 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004874 mCurrentCookedState.cookedPointerData.pointerProperties,
4875 mCurrentCookedState.cookedPointerData.pointerCoords,
4876 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004877 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004878 }
4879
4880 // Dispatch pointer down events using the new pointer locations.
4881 while (!downIdBits.isEmpty()) {
4882 uint32_t downId = downIdBits.clearFirstMarkedBit();
4883 dispatchedIdBits.markBit(downId);
4884
4885 if (dispatchedIdBits.count() == 1) {
4886 // First pointer is going down. Set down time.
4887 mDownTime = when;
4888 }
4889
4890 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004891 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004892 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004893 mCurrentCookedState.cookedPointerData.pointerProperties,
4894 mCurrentCookedState.cookedPointerData.pointerCoords,
4895 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004896 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004897 }
4898 }
4899}
4900
4901void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4902 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004903 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4904 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004905 int32_t metaState = getContext()->getGlobalMetaState();
4906 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004907 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004908 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004909 mLastCookedState.cookedPointerData.pointerProperties,
4910 mLastCookedState.cookedPointerData.pointerCoords,
4911 mLastCookedState.cookedPointerData.idToIndex,
4912 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4914 mSentHoverEnter = false;
4915 }
4916}
4917
4918void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004919 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4920 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921 int32_t metaState = getContext()->getGlobalMetaState();
4922 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004923 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004924 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004925 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004926 mCurrentCookedState.cookedPointerData.pointerProperties,
4927 mCurrentCookedState.cookedPointerData.pointerCoords,
4928 mCurrentCookedState.cookedPointerData.idToIndex,
4929 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004930 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4931 mSentHoverEnter = true;
4932 }
4933
4934 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004935 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004936 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004937 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004938 mCurrentCookedState.cookedPointerData.pointerProperties,
4939 mCurrentCookedState.cookedPointerData.pointerCoords,
4940 mCurrentCookedState.cookedPointerData.idToIndex,
4941 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4943 }
4944}
4945
Michael Wright7b159c92015-05-14 14:48:03 +01004946void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4947 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4948 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4949 const int32_t metaState = getContext()->getGlobalMetaState();
4950 int32_t buttonState = mLastCookedState.buttonState;
4951 while (!releasedButtons.isEmpty()) {
4952 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4953 buttonState &= ~actionButton;
4954 dispatchMotion(when, policyFlags, mSource,
4955 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4956 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004957 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004958 mCurrentCookedState.cookedPointerData.pointerProperties,
4959 mCurrentCookedState.cookedPointerData.pointerCoords,
4960 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4961 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4962 }
4963}
4964
4965void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4966 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4967 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4968 const int32_t metaState = getContext()->getGlobalMetaState();
4969 int32_t buttonState = mLastCookedState.buttonState;
4970 while (!pressedButtons.isEmpty()) {
4971 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4972 buttonState |= actionButton;
4973 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4974 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004975 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004976 mCurrentCookedState.cookedPointerData.pointerProperties,
4977 mCurrentCookedState.cookedPointerData.pointerCoords,
4978 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4979 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4980 }
4981}
4982
4983const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4984 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4985 return cookedPointerData.touchingIdBits;
4986 }
4987 return cookedPointerData.hoveringIdBits;
4988}
4989
Michael Wrightd02c5b62014-02-10 15:10:22 -08004990void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004991 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004992
Michael Wright842500e2015-03-13 17:32:02 -07004993 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004994 mCurrentCookedState.deviceTimestamp =
4995 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004996 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4997 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4998 mCurrentRawState.rawPointerData.hoveringIdBits;
4999 mCurrentCookedState.cookedPointerData.touchingIdBits =
5000 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005001
Michael Wright7b159c92015-05-14 14:48:03 +01005002 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
5003 mCurrentCookedState.buttonState = 0;
5004 } else {
5005 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
5006 }
5007
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 // Walk through the the active pointers and map device coordinates onto
5009 // surface coordinates and adjust for display orientation.
5010 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07005011 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005012
5013 // Size
5014 float touchMajor, touchMinor, toolMajor, toolMinor, size;
5015 switch (mCalibration.sizeCalibration) {
5016 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
5017 case Calibration::SIZE_CALIBRATION_DIAMETER:
5018 case Calibration::SIZE_CALIBRATION_BOX:
5019 case Calibration::SIZE_CALIBRATION_AREA:
5020 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
5021 touchMajor = in.touchMajor;
5022 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
5023 toolMajor = in.toolMajor;
5024 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
5025 size = mRawPointerAxes.touchMinor.valid
5026 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5027 } else if (mRawPointerAxes.touchMajor.valid) {
5028 toolMajor = touchMajor = in.touchMajor;
5029 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
5030 ? in.touchMinor : in.touchMajor;
5031 size = mRawPointerAxes.touchMinor.valid
5032 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5033 } else if (mRawPointerAxes.toolMajor.valid) {
5034 touchMajor = toolMajor = in.toolMajor;
5035 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5036 ? in.toolMinor : in.toolMajor;
5037 size = mRawPointerAxes.toolMinor.valid
5038 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5039 } else {
5040 ALOG_ASSERT(false, "No touch or tool axes. "
5041 "Size calibration should have been resolved to NONE.");
5042 touchMajor = 0;
5043 touchMinor = 0;
5044 toolMajor = 0;
5045 toolMinor = 0;
5046 size = 0;
5047 }
5048
5049 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005050 uint32_t touchingCount =
5051 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005052 if (touchingCount > 1) {
5053 touchMajor /= touchingCount;
5054 touchMinor /= touchingCount;
5055 toolMajor /= touchingCount;
5056 toolMinor /= touchingCount;
5057 size /= touchingCount;
5058 }
5059 }
5060
5061 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5062 touchMajor *= mGeometricScale;
5063 touchMinor *= mGeometricScale;
5064 toolMajor *= mGeometricScale;
5065 toolMinor *= mGeometricScale;
5066 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5067 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5068 touchMinor = touchMajor;
5069 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5070 toolMinor = toolMajor;
5071 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5072 touchMinor = touchMajor;
5073 toolMinor = toolMajor;
5074 }
5075
5076 mCalibration.applySizeScaleAndBias(&touchMajor);
5077 mCalibration.applySizeScaleAndBias(&touchMinor);
5078 mCalibration.applySizeScaleAndBias(&toolMajor);
5079 mCalibration.applySizeScaleAndBias(&toolMinor);
5080 size *= mSizeScale;
5081 break;
5082 default:
5083 touchMajor = 0;
5084 touchMinor = 0;
5085 toolMajor = 0;
5086 toolMinor = 0;
5087 size = 0;
5088 break;
5089 }
5090
5091 // Pressure
5092 float pressure;
5093 switch (mCalibration.pressureCalibration) {
5094 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5095 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5096 pressure = in.pressure * mPressureScale;
5097 break;
5098 default:
5099 pressure = in.isHovering ? 0 : 1;
5100 break;
5101 }
5102
5103 // Tilt and Orientation
5104 float tilt;
5105 float orientation;
5106 if (mHaveTilt) {
5107 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5108 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5109 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5110 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5111 } else {
5112 tilt = 0;
5113
5114 switch (mCalibration.orientationCalibration) {
5115 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5116 orientation = in.orientation * mOrientationScale;
5117 break;
5118 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5119 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5120 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5121 if (c1 != 0 || c2 != 0) {
5122 orientation = atan2f(c1, c2) * 0.5f;
5123 float confidence = hypotf(c1, c2);
5124 float scale = 1.0f + confidence / 16.0f;
5125 touchMajor *= scale;
5126 touchMinor /= scale;
5127 toolMajor *= scale;
5128 toolMinor /= scale;
5129 } else {
5130 orientation = 0;
5131 }
5132 break;
5133 }
5134 default:
5135 orientation = 0;
5136 }
5137 }
5138
5139 // Distance
5140 float distance;
5141 switch (mCalibration.distanceCalibration) {
5142 case Calibration::DISTANCE_CALIBRATION_SCALED:
5143 distance = in.distance * mDistanceScale;
5144 break;
5145 default:
5146 distance = 0;
5147 }
5148
5149 // Coverage
5150 int32_t rawLeft, rawTop, rawRight, rawBottom;
5151 switch (mCalibration.coverageCalibration) {
5152 case Calibration::COVERAGE_CALIBRATION_BOX:
5153 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5154 rawRight = in.toolMinor & 0x0000ffff;
5155 rawBottom = in.toolMajor & 0x0000ffff;
5156 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5157 break;
5158 default:
5159 rawLeft = rawTop = rawRight = rawBottom = 0;
5160 break;
5161 }
5162
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005163 // Adjust X,Y coords for device calibration
5164 // TODO: Adjust coverage coords?
5165 float xTransformed = in.x, yTransformed = in.y;
5166 mAffineTransform.applyTo(xTransformed, yTransformed);
5167
5168 // Adjust X, Y, and coverage coords for surface orientation.
5169 float x, y;
5170 float left, top, right, bottom;
5171
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 switch (mSurfaceOrientation) {
5173 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005174 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5175 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005176 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5177 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5178 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5179 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5180 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005181 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5183 }
5184 break;
5185 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005186 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005187 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005188 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5189 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5191 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5192 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005193 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005194 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5195 }
5196 break;
5197 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005198 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005199 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005200 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5201 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5203 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5204 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005205 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5207 }
5208 break;
5209 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005210 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5211 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005212 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5213 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5214 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5215 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5216 break;
5217 }
5218
5219 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005220 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005221 out.clear();
5222 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5223 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5224 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5225 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5226 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5227 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5228 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5229 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5230 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5231 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5232 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5233 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5234 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5235 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5236 } else {
5237 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5238 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5239 }
5240
5241 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005242 PointerProperties& properties =
5243 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 uint32_t id = in.id;
5245 properties.clear();
5246 properties.id = id;
5247 properties.toolType = in.toolType;
5248
5249 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005250 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005251 }
5252}
5253
5254void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5255 PointerUsage pointerUsage) {
5256 if (pointerUsage != mPointerUsage) {
5257 abortPointerUsage(when, policyFlags);
5258 mPointerUsage = pointerUsage;
5259 }
5260
5261 switch (mPointerUsage) {
5262 case POINTER_USAGE_GESTURES:
5263 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5264 break;
5265 case POINTER_USAGE_STYLUS:
5266 dispatchPointerStylus(when, policyFlags);
5267 break;
5268 case POINTER_USAGE_MOUSE:
5269 dispatchPointerMouse(when, policyFlags);
5270 break;
5271 default:
5272 break;
5273 }
5274}
5275
5276void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5277 switch (mPointerUsage) {
5278 case POINTER_USAGE_GESTURES:
5279 abortPointerGestures(when, policyFlags);
5280 break;
5281 case POINTER_USAGE_STYLUS:
5282 abortPointerStylus(when, policyFlags);
5283 break;
5284 case POINTER_USAGE_MOUSE:
5285 abortPointerMouse(when, policyFlags);
5286 break;
5287 default:
5288 break;
5289 }
5290
5291 mPointerUsage = POINTER_USAGE_NONE;
5292}
5293
5294void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5295 bool isTimeout) {
5296 // Update current gesture coordinates.
5297 bool cancelPreviousGesture, finishPreviousGesture;
5298 bool sendEvents = preparePointerGestures(when,
5299 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5300 if (!sendEvents) {
5301 return;
5302 }
5303 if (finishPreviousGesture) {
5304 cancelPreviousGesture = false;
5305 }
5306
5307 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005308 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5309 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 if (finishPreviousGesture || cancelPreviousGesture) {
5311 mPointerController->clearSpots();
5312 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005313
5314 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5315 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5316 mPointerGesture.currentGestureIdToIndex,
5317 mPointerGesture.currentGestureIdBits);
5318 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 } else {
5320 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5321 }
5322
5323 // Show or hide the pointer if needed.
5324 switch (mPointerGesture.currentGestureMode) {
5325 case PointerGesture::NEUTRAL:
5326 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005327 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5328 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 // Remind the user of where the pointer is after finishing a gesture with spots.
5330 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5331 }
5332 break;
5333 case PointerGesture::TAP:
5334 case PointerGesture::TAP_DRAG:
5335 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5336 case PointerGesture::HOVER:
5337 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005338 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005339 // Unfade the pointer when the current gesture manipulates the
5340 // area directly under the pointer.
5341 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5342 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005343 case PointerGesture::FREEFORM:
5344 // Fade the pointer when the current gesture manipulates a different
5345 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005346 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005347 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5348 } else {
5349 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5350 }
5351 break;
5352 }
5353
5354 // Send events!
5355 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005356 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005357
5358 // Update last coordinates of pointers that have moved so that we observe the new
5359 // pointer positions at the same time as other pointers that have just gone up.
5360 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5361 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5362 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5363 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5364 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5365 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5366 bool moveNeeded = false;
5367 if (down && !cancelPreviousGesture && !finishPreviousGesture
5368 && !mPointerGesture.lastGestureIdBits.isEmpty()
5369 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5370 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5371 & mPointerGesture.lastGestureIdBits.value);
5372 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5373 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5374 mPointerGesture.lastGestureProperties,
5375 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5376 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005377 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 moveNeeded = true;
5379 }
5380 }
5381
5382 // Send motion events for all pointers that went up or were canceled.
5383 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5384 if (!dispatchedGestureIdBits.isEmpty()) {
5385 if (cancelPreviousGesture) {
5386 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005387 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005388 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005389 mPointerGesture.lastGestureProperties,
5390 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005391 dispatchedGestureIdBits, -1, 0,
5392 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005393
5394 dispatchedGestureIdBits.clear();
5395 } else {
5396 BitSet32 upGestureIdBits;
5397 if (finishPreviousGesture) {
5398 upGestureIdBits = dispatchedGestureIdBits;
5399 } else {
5400 upGestureIdBits.value = dispatchedGestureIdBits.value
5401 & ~mPointerGesture.currentGestureIdBits.value;
5402 }
5403 while (!upGestureIdBits.isEmpty()) {
5404 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5405
5406 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005407 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005408 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005409 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 mPointerGesture.lastGestureProperties,
5411 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5412 dispatchedGestureIdBits, id,
5413 0, 0, mPointerGesture.downTime);
5414
5415 dispatchedGestureIdBits.clearBit(id);
5416 }
5417 }
5418 }
5419
5420 // Send motion events for all pointers that moved.
5421 if (moveNeeded) {
5422 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005423 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005424 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005425 mPointerGesture.currentGestureProperties,
5426 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5427 dispatchedGestureIdBits, -1,
5428 0, 0, mPointerGesture.downTime);
5429 }
5430
5431 // Send motion events for all pointers that went down.
5432 if (down) {
5433 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5434 & ~dispatchedGestureIdBits.value);
5435 while (!downGestureIdBits.isEmpty()) {
5436 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5437 dispatchedGestureIdBits.markBit(id);
5438
5439 if (dispatchedGestureIdBits.count() == 1) {
5440 mPointerGesture.downTime = when;
5441 }
5442
5443 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005444 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005445 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005446 mPointerGesture.currentGestureProperties,
5447 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5448 dispatchedGestureIdBits, id,
5449 0, 0, mPointerGesture.downTime);
5450 }
5451 }
5452
5453 // Send motion events for hover.
5454 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5455 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005456 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005457 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005458 mPointerGesture.currentGestureProperties,
5459 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5460 mPointerGesture.currentGestureIdBits, -1,
5461 0, 0, mPointerGesture.downTime);
5462 } else if (dispatchedGestureIdBits.isEmpty()
5463 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5464 // Synthesize a hover move event after all pointers go up to indicate that
5465 // the pointer is hovering again even if the user is not currently touching
5466 // the touch pad. This ensures that a view will receive a fresh hover enter
5467 // event after a tap.
5468 float x, y;
5469 mPointerController->getPosition(&x, &y);
5470
5471 PointerProperties pointerProperties;
5472 pointerProperties.clear();
5473 pointerProperties.id = 0;
5474 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5475
5476 PointerCoords pointerCoords;
5477 pointerCoords.clear();
5478 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5479 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5480
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005481 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005482 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005483 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005484 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005485 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005486 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005487 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 getListener()->notifyMotion(&args);
5489 }
5490
5491 // Update state.
5492 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5493 if (!down) {
5494 mPointerGesture.lastGestureIdBits.clear();
5495 } else {
5496 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5497 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5498 uint32_t id = idBits.clearFirstMarkedBit();
5499 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5500 mPointerGesture.lastGestureProperties[index].copyFrom(
5501 mPointerGesture.currentGestureProperties[index]);
5502 mPointerGesture.lastGestureCoords[index].copyFrom(
5503 mPointerGesture.currentGestureCoords[index]);
5504 mPointerGesture.lastGestureIdToIndex[id] = index;
5505 }
5506 }
5507}
5508
5509void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5510 // Cancel previously dispatches pointers.
5511 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5512 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005513 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005515 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005516 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005517 mPointerGesture.lastGestureProperties,
5518 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5519 mPointerGesture.lastGestureIdBits, -1,
5520 0, 0, mPointerGesture.downTime);
5521 }
5522
5523 // Reset the current pointer gesture.
5524 mPointerGesture.reset();
5525 mPointerVelocityControl.reset();
5526
5527 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005528 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005529 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5530 mPointerController->clearSpots();
5531 }
5532}
5533
5534bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5535 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5536 *outCancelPreviousGesture = false;
5537 *outFinishPreviousGesture = false;
5538
5539 // Handle TAP timeout.
5540 if (isTimeout) {
5541#if DEBUG_GESTURES
5542 ALOGD("Gestures: Processing timeout");
5543#endif
5544
5545 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5546 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5547 // The tap/drag timeout has not yet expired.
5548 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5549 + mConfig.pointerGestureTapDragInterval);
5550 } else {
5551 // The tap is finished.
5552#if DEBUG_GESTURES
5553 ALOGD("Gestures: TAP finished");
5554#endif
5555 *outFinishPreviousGesture = true;
5556
5557 mPointerGesture.activeGestureId = -1;
5558 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5559 mPointerGesture.currentGestureIdBits.clear();
5560
5561 mPointerVelocityControl.reset();
5562 return true;
5563 }
5564 }
5565
5566 // We did not handle this timeout.
5567 return false;
5568 }
5569
Michael Wright842500e2015-03-13 17:32:02 -07005570 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5571 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572
5573 // Update the velocity tracker.
5574 {
5575 VelocityTracker::Position positions[MAX_POINTERS];
5576 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005577 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005578 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005579 const RawPointerData::Pointer& pointer =
5580 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581 positions[count].x = pointer.x * mPointerXMovementScale;
5582 positions[count].y = pointer.y * mPointerYMovementScale;
5583 }
5584 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005585 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005586 }
5587
5588 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5589 // to NEUTRAL, then we should not generate tap event.
5590 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5591 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5592 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5593 mPointerGesture.resetTap();
5594 }
5595
5596 // Pick a new active touch id if needed.
5597 // Choose an arbitrary pointer that just went down, if there is one.
5598 // Otherwise choose an arbitrary remaining pointer.
5599 // This guarantees we always have an active touch id when there is at least one pointer.
5600 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005601 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5602 int32_t activeTouchId = lastActiveTouchId;
5603 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005604 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005605 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005606 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005607 mPointerGesture.firstTouchTime = when;
5608 }
Michael Wright842500e2015-03-13 17:32:02 -07005609 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005610 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005611 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005612 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 } else {
5614 activeTouchId = mPointerGesture.activeTouchId = -1;
5615 }
5616 }
5617
5618 // Determine whether we are in quiet time.
5619 bool isQuietTime = false;
5620 if (activeTouchId < 0) {
5621 mPointerGesture.resetQuietTime();
5622 } else {
5623 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5624 if (!isQuietTime) {
5625 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5626 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5627 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5628 && currentFingerCount < 2) {
5629 // Enter quiet time when exiting swipe or freeform state.
5630 // This is to prevent accidentally entering the hover state and flinging the
5631 // pointer when finishing a swipe and there is still one pointer left onscreen.
5632 isQuietTime = true;
5633 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5634 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005635 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 // Enter quiet time when releasing the button and there are still two or more
5637 // fingers down. This may indicate that one finger was used to press the button
5638 // but it has not gone up yet.
5639 isQuietTime = true;
5640 }
5641 if (isQuietTime) {
5642 mPointerGesture.quietTime = when;
5643 }
5644 }
5645 }
5646
5647 // Switch states based on button and pointer state.
5648 if (isQuietTime) {
5649 // Case 1: Quiet time. (QUIET)
5650#if DEBUG_GESTURES
5651 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5652 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5653#endif
5654 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5655 *outFinishPreviousGesture = true;
5656 }
5657
5658 mPointerGesture.activeGestureId = -1;
5659 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5660 mPointerGesture.currentGestureIdBits.clear();
5661
5662 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005663 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005664 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5665 // The pointer follows the active touch point.
5666 // Emit DOWN, MOVE, UP events at the pointer location.
5667 //
5668 // Only the active touch matters; other fingers are ignored. This policy helps
5669 // to handle the case where the user places a second finger on the touch pad
5670 // to apply the necessary force to depress an integrated button below the surface.
5671 // We don't want the second finger to be delivered to applications.
5672 //
5673 // For this to work well, we need to make sure to track the pointer that is really
5674 // active. If the user first puts one finger down to click then adds another
5675 // finger to drag then the active pointer should switch to the finger that is
5676 // being dragged.
5677#if DEBUG_GESTURES
5678 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5679 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5680#endif
5681 // Reset state when just starting.
5682 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5683 *outFinishPreviousGesture = true;
5684 mPointerGesture.activeGestureId = 0;
5685 }
5686
5687 // Switch pointers if needed.
5688 // Find the fastest pointer and follow it.
5689 if (activeTouchId >= 0 && currentFingerCount > 1) {
5690 int32_t bestId = -1;
5691 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005692 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005693 uint32_t id = idBits.clearFirstMarkedBit();
5694 float vx, vy;
5695 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5696 float speed = hypotf(vx, vy);
5697 if (speed > bestSpeed) {
5698 bestId = id;
5699 bestSpeed = speed;
5700 }
5701 }
5702 }
5703 if (bestId >= 0 && bestId != activeTouchId) {
5704 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005705#if DEBUG_GESTURES
5706 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5707 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5708#endif
5709 }
5710 }
5711
Jun Mukaifa1706a2015-12-03 01:14:46 -08005712 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005713 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005715 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005717 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005718 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5719 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005720
5721 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5722 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5723
5724 // Move the pointer using a relative motion.
5725 // When using spots, the click will occur at the position of the anchor
5726 // spot and all other spots will move there.
5727 mPointerController->move(deltaX, deltaY);
5728 } else {
5729 mPointerVelocityControl.reset();
5730 }
5731
5732 float x, y;
5733 mPointerController->getPosition(&x, &y);
5734
5735 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5736 mPointerGesture.currentGestureIdBits.clear();
5737 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5738 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5739 mPointerGesture.currentGestureProperties[0].clear();
5740 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5741 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5742 mPointerGesture.currentGestureCoords[0].clear();
5743 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5744 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5745 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5746 } else if (currentFingerCount == 0) {
5747 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5748 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5749 *outFinishPreviousGesture = true;
5750 }
5751
5752 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5753 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5754 bool tapped = false;
5755 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5756 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5757 && lastFingerCount == 1) {
5758 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5759 float x, y;
5760 mPointerController->getPosition(&x, &y);
5761 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5762 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5763#if DEBUG_GESTURES
5764 ALOGD("Gestures: TAP");
5765#endif
5766
5767 mPointerGesture.tapUpTime = when;
5768 getContext()->requestTimeoutAtTime(when
5769 + mConfig.pointerGestureTapDragInterval);
5770
5771 mPointerGesture.activeGestureId = 0;
5772 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5773 mPointerGesture.currentGestureIdBits.clear();
5774 mPointerGesture.currentGestureIdBits.markBit(
5775 mPointerGesture.activeGestureId);
5776 mPointerGesture.currentGestureIdToIndex[
5777 mPointerGesture.activeGestureId] = 0;
5778 mPointerGesture.currentGestureProperties[0].clear();
5779 mPointerGesture.currentGestureProperties[0].id =
5780 mPointerGesture.activeGestureId;
5781 mPointerGesture.currentGestureProperties[0].toolType =
5782 AMOTION_EVENT_TOOL_TYPE_FINGER;
5783 mPointerGesture.currentGestureCoords[0].clear();
5784 mPointerGesture.currentGestureCoords[0].setAxisValue(
5785 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5786 mPointerGesture.currentGestureCoords[0].setAxisValue(
5787 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5788 mPointerGesture.currentGestureCoords[0].setAxisValue(
5789 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5790
5791 tapped = true;
5792 } else {
5793#if DEBUG_GESTURES
5794 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5795 x - mPointerGesture.tapX,
5796 y - mPointerGesture.tapY);
5797#endif
5798 }
5799 } else {
5800#if DEBUG_GESTURES
5801 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5802 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5803 (when - mPointerGesture.tapDownTime) * 0.000001f);
5804 } else {
5805 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5806 }
5807#endif
5808 }
5809 }
5810
5811 mPointerVelocityControl.reset();
5812
5813 if (!tapped) {
5814#if DEBUG_GESTURES
5815 ALOGD("Gestures: NEUTRAL");
5816#endif
5817 mPointerGesture.activeGestureId = -1;
5818 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5819 mPointerGesture.currentGestureIdBits.clear();
5820 }
5821 } else if (currentFingerCount == 1) {
5822 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5823 // The pointer follows the active touch point.
5824 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5825 // When in TAP_DRAG, emit MOVE events at the pointer location.
5826 ALOG_ASSERT(activeTouchId >= 0);
5827
5828 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5829 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5830 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5831 float x, y;
5832 mPointerController->getPosition(&x, &y);
5833 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5834 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5835 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5836 } else {
5837#if DEBUG_GESTURES
5838 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5839 x - mPointerGesture.tapX,
5840 y - mPointerGesture.tapY);
5841#endif
5842 }
5843 } else {
5844#if DEBUG_GESTURES
5845 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5846 (when - mPointerGesture.tapUpTime) * 0.000001f);
5847#endif
5848 }
5849 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5850 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5851 }
5852
Jun Mukaifa1706a2015-12-03 01:14:46 -08005853 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005854 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005855 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005856 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005857 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005858 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005859 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5860 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005861
5862 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5863 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5864
5865 // Move the pointer using a relative motion.
5866 // When using spots, the hover or drag will occur at the position of the anchor spot.
5867 mPointerController->move(deltaX, deltaY);
5868 } else {
5869 mPointerVelocityControl.reset();
5870 }
5871
5872 bool down;
5873 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5874#if DEBUG_GESTURES
5875 ALOGD("Gestures: TAP_DRAG");
5876#endif
5877 down = true;
5878 } else {
5879#if DEBUG_GESTURES
5880 ALOGD("Gestures: HOVER");
5881#endif
5882 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5883 *outFinishPreviousGesture = true;
5884 }
5885 mPointerGesture.activeGestureId = 0;
5886 down = false;
5887 }
5888
5889 float x, y;
5890 mPointerController->getPosition(&x, &y);
5891
5892 mPointerGesture.currentGestureIdBits.clear();
5893 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5894 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5895 mPointerGesture.currentGestureProperties[0].clear();
5896 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5897 mPointerGesture.currentGestureProperties[0].toolType =
5898 AMOTION_EVENT_TOOL_TYPE_FINGER;
5899 mPointerGesture.currentGestureCoords[0].clear();
5900 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5901 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5902 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5903 down ? 1.0f : 0.0f);
5904
5905 if (lastFingerCount == 0 && currentFingerCount != 0) {
5906 mPointerGesture.resetTap();
5907 mPointerGesture.tapDownTime = when;
5908 mPointerGesture.tapX = x;
5909 mPointerGesture.tapY = y;
5910 }
5911 } else {
5912 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5913 // We need to provide feedback for each finger that goes down so we cannot wait
5914 // for the fingers to move before deciding what to do.
5915 //
5916 // The ambiguous case is deciding what to do when there are two fingers down but they
5917 // have not moved enough to determine whether they are part of a drag or part of a
5918 // freeform gesture, or just a press or long-press at the pointer location.
5919 //
5920 // When there are two fingers we start with the PRESS hypothesis and we generate a
5921 // down at the pointer location.
5922 //
5923 // When the two fingers move enough or when additional fingers are added, we make
5924 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5925 ALOG_ASSERT(activeTouchId >= 0);
5926
5927 bool settled = when >= mPointerGesture.firstTouchTime
5928 + mConfig.pointerGestureMultitouchSettleInterval;
5929 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5930 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5931 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5932 *outFinishPreviousGesture = true;
5933 } else if (!settled && currentFingerCount > lastFingerCount) {
5934 // Additional pointers have gone down but not yet settled.
5935 // Reset the gesture.
5936#if DEBUG_GESTURES
5937 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5938 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5939 + mConfig.pointerGestureMultitouchSettleInterval - when)
5940 * 0.000001f);
5941#endif
5942 *outCancelPreviousGesture = true;
5943 } else {
5944 // Continue previous gesture.
5945 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5946 }
5947
5948 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5949 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5950 mPointerGesture.activeGestureId = 0;
5951 mPointerGesture.referenceIdBits.clear();
5952 mPointerVelocityControl.reset();
5953
5954 // Use the centroid and pointer location as the reference points for the gesture.
5955#if DEBUG_GESTURES
5956 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5957 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5958 + mConfig.pointerGestureMultitouchSettleInterval - when)
5959 * 0.000001f);
5960#endif
Michael Wright842500e2015-03-13 17:32:02 -07005961 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005962 &mPointerGesture.referenceTouchX,
5963 &mPointerGesture.referenceTouchY);
5964 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5965 &mPointerGesture.referenceGestureY);
5966 }
5967
5968 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005969 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5971 uint32_t id = idBits.clearFirstMarkedBit();
5972 mPointerGesture.referenceDeltas[id].dx = 0;
5973 mPointerGesture.referenceDeltas[id].dy = 0;
5974 }
Michael Wright842500e2015-03-13 17:32:02 -07005975 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005976
5977 // Add delta for all fingers and calculate a common movement delta.
5978 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005979 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5980 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005981 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5982 bool first = (idBits == commonIdBits);
5983 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005984 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5985 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5987 delta.dx += cpd.x - lpd.x;
5988 delta.dy += cpd.y - lpd.y;
5989
5990 if (first) {
5991 commonDeltaX = delta.dx;
5992 commonDeltaY = delta.dy;
5993 } else {
5994 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5995 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5996 }
5997 }
5998
5999 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
6000 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
6001 float dist[MAX_POINTER_ID + 1];
6002 int32_t distOverThreshold = 0;
6003 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6004 uint32_t id = idBits.clearFirstMarkedBit();
6005 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6006 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
6007 delta.dy * mPointerYZoomScale);
6008 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
6009 distOverThreshold += 1;
6010 }
6011 }
6012
6013 // Only transition when at least two pointers have moved further than
6014 // the minimum distance threshold.
6015 if (distOverThreshold >= 2) {
6016 if (currentFingerCount > 2) {
6017 // There are more than two pointers, switch to FREEFORM.
6018#if DEBUG_GESTURES
6019 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
6020 currentFingerCount);
6021#endif
6022 *outCancelPreviousGesture = true;
6023 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6024 } else {
6025 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07006026 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006027 uint32_t id1 = idBits.clearFirstMarkedBit();
6028 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07006029 const RawPointerData::Pointer& p1 =
6030 mCurrentRawState.rawPointerData.pointerForId(id1);
6031 const RawPointerData::Pointer& p2 =
6032 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006033 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
6034 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
6035 // There are two pointers but they are too far apart for a SWIPE,
6036 // switch to FREEFORM.
6037#if DEBUG_GESTURES
6038 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6039 mutualDistance, mPointerGestureMaxSwipeWidth);
6040#endif
6041 *outCancelPreviousGesture = true;
6042 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6043 } else {
6044 // There are two pointers. Wait for both pointers to start moving
6045 // before deciding whether this is a SWIPE or FREEFORM gesture.
6046 float dist1 = dist[id1];
6047 float dist2 = dist[id2];
6048 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6049 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6050 // Calculate the dot product of the displacement vectors.
6051 // When the vectors are oriented in approximately the same direction,
6052 // the angle betweeen them is near zero and the cosine of the angle
6053 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6054 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6055 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6056 float dx1 = delta1.dx * mPointerXZoomScale;
6057 float dy1 = delta1.dy * mPointerYZoomScale;
6058 float dx2 = delta2.dx * mPointerXZoomScale;
6059 float dy2 = delta2.dy * mPointerYZoomScale;
6060 float dot = dx1 * dx2 + dy1 * dy2;
6061 float cosine = dot / (dist1 * dist2); // denominator always > 0
6062 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6063 // Pointers are moving in the same direction. Switch to SWIPE.
6064#if DEBUG_GESTURES
6065 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6066 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6067 "cosine %0.3f >= %0.3f",
6068 dist1, mConfig.pointerGestureMultitouchMinDistance,
6069 dist2, mConfig.pointerGestureMultitouchMinDistance,
6070 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6071#endif
6072 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6073 } else {
6074 // Pointers are moving in different directions. Switch to FREEFORM.
6075#if DEBUG_GESTURES
6076 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6077 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6078 "cosine %0.3f < %0.3f",
6079 dist1, mConfig.pointerGestureMultitouchMinDistance,
6080 dist2, mConfig.pointerGestureMultitouchMinDistance,
6081 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6082#endif
6083 *outCancelPreviousGesture = true;
6084 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6085 }
6086 }
6087 }
6088 }
6089 }
6090 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6091 // Switch from SWIPE to FREEFORM if additional pointers go down.
6092 // Cancel previous gesture.
6093 if (currentFingerCount > 2) {
6094#if DEBUG_GESTURES
6095 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6096 currentFingerCount);
6097#endif
6098 *outCancelPreviousGesture = true;
6099 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6100 }
6101 }
6102
6103 // Move the reference points based on the overall group motion of the fingers
6104 // except in PRESS mode while waiting for a transition to occur.
6105 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6106 && (commonDeltaX || commonDeltaY)) {
6107 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6108 uint32_t id = idBits.clearFirstMarkedBit();
6109 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6110 delta.dx = 0;
6111 delta.dy = 0;
6112 }
6113
6114 mPointerGesture.referenceTouchX += commonDeltaX;
6115 mPointerGesture.referenceTouchY += commonDeltaY;
6116
6117 commonDeltaX *= mPointerXMovementScale;
6118 commonDeltaY *= mPointerYMovementScale;
6119
6120 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6121 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6122
6123 mPointerGesture.referenceGestureX += commonDeltaX;
6124 mPointerGesture.referenceGestureY += commonDeltaY;
6125 }
6126
6127 // Report gestures.
6128 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6129 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6130 // PRESS or SWIPE mode.
6131#if DEBUG_GESTURES
6132 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6133 "activeGestureId=%d, currentTouchPointerCount=%d",
6134 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6135#endif
6136 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6137
6138 mPointerGesture.currentGestureIdBits.clear();
6139 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6140 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6141 mPointerGesture.currentGestureProperties[0].clear();
6142 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6143 mPointerGesture.currentGestureProperties[0].toolType =
6144 AMOTION_EVENT_TOOL_TYPE_FINGER;
6145 mPointerGesture.currentGestureCoords[0].clear();
6146 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6147 mPointerGesture.referenceGestureX);
6148 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6149 mPointerGesture.referenceGestureY);
6150 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6151 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6152 // FREEFORM mode.
6153#if DEBUG_GESTURES
6154 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6155 "activeGestureId=%d, currentTouchPointerCount=%d",
6156 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6157#endif
6158 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6159
6160 mPointerGesture.currentGestureIdBits.clear();
6161
6162 BitSet32 mappedTouchIdBits;
6163 BitSet32 usedGestureIdBits;
6164 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6165 // Initially, assign the active gesture id to the active touch point
6166 // if there is one. No other touch id bits are mapped yet.
6167 if (!*outCancelPreviousGesture) {
6168 mappedTouchIdBits.markBit(activeTouchId);
6169 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6170 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6171 mPointerGesture.activeGestureId;
6172 } else {
6173 mPointerGesture.activeGestureId = -1;
6174 }
6175 } else {
6176 // Otherwise, assume we mapped all touches from the previous frame.
6177 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006178 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6179 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6181
6182 // Check whether we need to choose a new active gesture id because the
6183 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006184 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6185 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006186 !upTouchIdBits.isEmpty(); ) {
6187 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6188 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6189 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6190 mPointerGesture.activeGestureId = -1;
6191 break;
6192 }
6193 }
6194 }
6195
6196#if DEBUG_GESTURES
6197 ALOGD("Gestures: FREEFORM follow up "
6198 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6199 "activeGestureId=%d",
6200 mappedTouchIdBits.value, usedGestureIdBits.value,
6201 mPointerGesture.activeGestureId);
6202#endif
6203
Michael Wright842500e2015-03-13 17:32:02 -07006204 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 for (uint32_t i = 0; i < currentFingerCount; i++) {
6206 uint32_t touchId = idBits.clearFirstMarkedBit();
6207 uint32_t gestureId;
6208 if (!mappedTouchIdBits.hasBit(touchId)) {
6209 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6210 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6211#if DEBUG_GESTURES
6212 ALOGD("Gestures: FREEFORM "
6213 "new mapping for touch id %d -> gesture id %d",
6214 touchId, gestureId);
6215#endif
6216 } else {
6217 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6218#if DEBUG_GESTURES
6219 ALOGD("Gestures: FREEFORM "
6220 "existing mapping for touch id %d -> gesture id %d",
6221 touchId, gestureId);
6222#endif
6223 }
6224 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6225 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6226
6227 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006228 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6230 * mPointerXZoomScale;
6231 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6232 * mPointerYZoomScale;
6233 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6234
6235 mPointerGesture.currentGestureProperties[i].clear();
6236 mPointerGesture.currentGestureProperties[i].id = gestureId;
6237 mPointerGesture.currentGestureProperties[i].toolType =
6238 AMOTION_EVENT_TOOL_TYPE_FINGER;
6239 mPointerGesture.currentGestureCoords[i].clear();
6240 mPointerGesture.currentGestureCoords[i].setAxisValue(
6241 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6242 mPointerGesture.currentGestureCoords[i].setAxisValue(
6243 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6244 mPointerGesture.currentGestureCoords[i].setAxisValue(
6245 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6246 }
6247
6248 if (mPointerGesture.activeGestureId < 0) {
6249 mPointerGesture.activeGestureId =
6250 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6251#if DEBUG_GESTURES
6252 ALOGD("Gestures: FREEFORM new "
6253 "activeGestureId=%d", mPointerGesture.activeGestureId);
6254#endif
6255 }
6256 }
6257 }
6258
Michael Wright842500e2015-03-13 17:32:02 -07006259 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006260
6261#if DEBUG_GESTURES
6262 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6263 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6264 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6265 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6266 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6267 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6268 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6269 uint32_t id = idBits.clearFirstMarkedBit();
6270 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6271 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6272 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6273 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6274 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6275 id, index, properties.toolType,
6276 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6277 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6278 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6279 }
6280 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6281 uint32_t id = idBits.clearFirstMarkedBit();
6282 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6283 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6284 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6285 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6286 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6287 id, index, properties.toolType,
6288 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6289 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6290 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6291 }
6292#endif
6293 return true;
6294}
6295
6296void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6297 mPointerSimple.currentCoords.clear();
6298 mPointerSimple.currentProperties.clear();
6299
6300 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006301 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6302 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6303 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6304 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6305 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006306 mPointerController->setPosition(x, y);
6307
Michael Wright842500e2015-03-13 17:32:02 -07006308 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006309 down = !hovering;
6310
6311 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006312 mPointerSimple.currentCoords.copyFrom(
6313 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006314 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6315 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6316 mPointerSimple.currentProperties.id = 0;
6317 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006318 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 } else {
6320 down = false;
6321 hovering = false;
6322 }
6323
6324 dispatchPointerSimple(when, policyFlags, down, hovering);
6325}
6326
6327void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6328 abortPointerSimple(when, policyFlags);
6329}
6330
6331void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6332 mPointerSimple.currentCoords.clear();
6333 mPointerSimple.currentProperties.clear();
6334
6335 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006336 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6337 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6338 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006339 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006340 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6341 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006342 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006343 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006345 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006346 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006347 * mPointerYMovementScale;
6348
6349 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6350 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6351
6352 mPointerController->move(deltaX, deltaY);
6353 } else {
6354 mPointerVelocityControl.reset();
6355 }
6356
Michael Wright842500e2015-03-13 17:32:02 -07006357 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006358 hovering = !down;
6359
6360 float x, y;
6361 mPointerController->getPosition(&x, &y);
6362 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006363 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006364 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6365 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6366 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6367 hovering ? 0.0f : 1.0f);
6368 mPointerSimple.currentProperties.id = 0;
6369 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006370 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006371 } else {
6372 mPointerVelocityControl.reset();
6373
6374 down = false;
6375 hovering = false;
6376 }
6377
6378 dispatchPointerSimple(when, policyFlags, down, hovering);
6379}
6380
6381void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6382 abortPointerSimple(when, policyFlags);
6383
6384 mPointerVelocityControl.reset();
6385}
6386
6387void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6388 bool down, bool hovering) {
6389 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006390 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006391
Yi Kong9b14ac62018-07-17 13:48:38 -07006392 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006393 if (down || hovering) {
6394 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6395 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006396 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006397 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6398 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6399 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6400 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006401 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006402 }
6403
6404 if (mPointerSimple.down && !down) {
6405 mPointerSimple.down = false;
6406
6407 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006408 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006409 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006410 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6411 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006412 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6413 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006414 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415 getListener()->notifyMotion(&args);
6416 }
6417
6418 if (mPointerSimple.hovering && !hovering) {
6419 mPointerSimple.hovering = false;
6420
6421 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006422 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6423 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006424 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6425 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6427 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006428 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006429 getListener()->notifyMotion(&args);
6430 }
6431
6432 if (down) {
6433 if (!mPointerSimple.down) {
6434 mPointerSimple.down = true;
6435 mPointerSimple.downTime = when;
6436
6437 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006438 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6439 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006440 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6441 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006442 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006443 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6444 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006445 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 getListener()->notifyMotion(&args);
6447 }
6448
6449 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006450 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6451 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006452 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6453 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006454 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6455 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006456 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006457 getListener()->notifyMotion(&args);
6458 }
6459
6460 if (hovering) {
6461 if (!mPointerSimple.hovering) {
6462 mPointerSimple.hovering = true;
6463
6464 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006465 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6466 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006467 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006468 mCurrentRawState.buttonState, MotionClassification::NONE,
6469 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006470 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6471 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006472 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006473 getListener()->notifyMotion(&args);
6474 }
6475
6476 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006477 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6478 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006479 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006480 mCurrentRawState.buttonState, MotionClassification::NONE,
6481 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006482 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6483 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006484 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006485 getListener()->notifyMotion(&args);
6486 }
6487
Michael Wright842500e2015-03-13 17:32:02 -07006488 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6489 float vscroll = mCurrentRawState.rawVScroll;
6490 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006491 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6492 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493
6494 // Send scroll.
6495 PointerCoords pointerCoords;
6496 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6497 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6498 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6499
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006500 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6501 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006502 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6503 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006504 1, &mPointerSimple.currentProperties, &pointerCoords,
6505 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006506 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507 getListener()->notifyMotion(&args);
6508 }
6509
6510 // Save state.
6511 if (down || hovering) {
6512 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6513 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6514 } else {
6515 mPointerSimple.reset();
6516 }
6517}
6518
6519void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6520 mPointerSimple.currentCoords.clear();
6521 mPointerSimple.currentProperties.clear();
6522
6523 dispatchPointerSimple(when, policyFlags, false, false);
6524}
6525
6526void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006527 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006528 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006529 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006530 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6531 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006532 PointerCoords pointerCoords[MAX_POINTERS];
6533 PointerProperties pointerProperties[MAX_POINTERS];
6534 uint32_t pointerCount = 0;
6535 while (!idBits.isEmpty()) {
6536 uint32_t id = idBits.clearFirstMarkedBit();
6537 uint32_t index = idToIndex[id];
6538 pointerProperties[pointerCount].copyFrom(properties[index]);
6539 pointerCoords[pointerCount].copyFrom(coords[index]);
6540
6541 if (changedId >= 0 && id == uint32_t(changedId)) {
6542 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6543 }
6544
6545 pointerCount += 1;
6546 }
6547
6548 ALOG_ASSERT(pointerCount != 0);
6549
6550 if (changedId >= 0 && pointerCount == 1) {
6551 // Replace initial down and final up action.
6552 // We can compare the action without masking off the changed pointer index
6553 // because we know the index is 0.
6554 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6555 action = AMOTION_EVENT_ACTION_DOWN;
6556 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6557 action = AMOTION_EVENT_ACTION_UP;
6558 } else {
6559 // Can't happen.
6560 ALOG_ASSERT(false);
6561 }
6562 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006563 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006564 const int32_t deviceId = getDeviceId();
6565 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6566 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006567 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006568 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6569 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006570 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006571 getListener()->notifyMotion(&args);
6572}
6573
6574bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6575 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6576 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6577 BitSet32 idBits) const {
6578 bool changed = false;
6579 while (!idBits.isEmpty()) {
6580 uint32_t id = idBits.clearFirstMarkedBit();
6581 uint32_t inIndex = inIdToIndex[id];
6582 uint32_t outIndex = outIdToIndex[id];
6583
6584 const PointerProperties& curInProperties = inProperties[inIndex];
6585 const PointerCoords& curInCoords = inCoords[inIndex];
6586 PointerProperties& curOutProperties = outProperties[outIndex];
6587 PointerCoords& curOutCoords = outCoords[outIndex];
6588
6589 if (curInProperties != curOutProperties) {
6590 curOutProperties.copyFrom(curInProperties);
6591 changed = true;
6592 }
6593
6594 if (curInCoords != curOutCoords) {
6595 curOutCoords.copyFrom(curInCoords);
6596 changed = true;
6597 }
6598 }
6599 return changed;
6600}
6601
6602void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006603 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006604 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6605 }
6606}
6607
Jeff Brownc9aa6282015-02-11 19:03:28 -08006608void TouchInputMapper::cancelTouch(nsecs_t when) {
6609 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006610 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006611}
6612
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006614 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006615 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006616 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006617 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6618 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6619 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006620}
6621
6622const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6623 int32_t x, int32_t y) {
6624 size_t numVirtualKeys = mVirtualKeys.size();
6625 for (size_t i = 0; i < numVirtualKeys; i++) {
6626 const VirtualKey& virtualKey = mVirtualKeys[i];
6627
6628#if DEBUG_VIRTUAL_KEYS
6629 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6630 "left=%d, top=%d, right=%d, bottom=%d",
6631 x, y,
6632 virtualKey.keyCode, virtualKey.scanCode,
6633 virtualKey.hitLeft, virtualKey.hitTop,
6634 virtualKey.hitRight, virtualKey.hitBottom);
6635#endif
6636
6637 if (virtualKey.isHit(x, y)) {
6638 return & virtualKey;
6639 }
6640 }
6641
Yi Kong9b14ac62018-07-17 13:48:38 -07006642 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006643}
6644
Michael Wright842500e2015-03-13 17:32:02 -07006645void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6646 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6647 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006648
Michael Wright842500e2015-03-13 17:32:02 -07006649 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006650
6651 if (currentPointerCount == 0) {
6652 // No pointers to assign.
6653 return;
6654 }
6655
6656 if (lastPointerCount == 0) {
6657 // All pointers are new.
6658 for (uint32_t i = 0; i < currentPointerCount; i++) {
6659 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006660 current->rawPointerData.pointers[i].id = id;
6661 current->rawPointerData.idToIndex[id] = i;
6662 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006663 }
6664 return;
6665 }
6666
6667 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006668 && current->rawPointerData.pointers[0].toolType
6669 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006670 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006671 uint32_t id = last->rawPointerData.pointers[0].id;
6672 current->rawPointerData.pointers[0].id = id;
6673 current->rawPointerData.idToIndex[id] = 0;
6674 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006675 return;
6676 }
6677
6678 // General case.
6679 // We build a heap of squared euclidean distances between current and last pointers
6680 // associated with the current and last pointer indices. Then, we find the best
6681 // match (by distance) for each current pointer.
6682 // The pointers must have the same tool type but it is possible for them to
6683 // transition from hovering to touching or vice-versa while retaining the same id.
6684 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6685
6686 uint32_t heapSize = 0;
6687 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6688 currentPointerIndex++) {
6689 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6690 lastPointerIndex++) {
6691 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006692 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006693 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006694 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006695 if (currentPointer.toolType == lastPointer.toolType) {
6696 int64_t deltaX = currentPointer.x - lastPointer.x;
6697 int64_t deltaY = currentPointer.y - lastPointer.y;
6698
6699 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6700
6701 // Insert new element into the heap (sift up).
6702 heap[heapSize].currentPointerIndex = currentPointerIndex;
6703 heap[heapSize].lastPointerIndex = lastPointerIndex;
6704 heap[heapSize].distance = distance;
6705 heapSize += 1;
6706 }
6707 }
6708 }
6709
6710 // Heapify
6711 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6712 startIndex -= 1;
6713 for (uint32_t parentIndex = startIndex; ;) {
6714 uint32_t childIndex = parentIndex * 2 + 1;
6715 if (childIndex >= heapSize) {
6716 break;
6717 }
6718
6719 if (childIndex + 1 < heapSize
6720 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6721 childIndex += 1;
6722 }
6723
6724 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6725 break;
6726 }
6727
6728 swap(heap[parentIndex], heap[childIndex]);
6729 parentIndex = childIndex;
6730 }
6731 }
6732
6733#if DEBUG_POINTER_ASSIGNMENT
6734 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6735 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006736 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006737 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6738 heap[i].distance);
6739 }
6740#endif
6741
6742 // Pull matches out by increasing order of distance.
6743 // To avoid reassigning pointers that have already been matched, the loop keeps track
6744 // of which last and current pointers have been matched using the matchedXXXBits variables.
6745 // It also tracks the used pointer id bits.
6746 BitSet32 matchedLastBits(0);
6747 BitSet32 matchedCurrentBits(0);
6748 BitSet32 usedIdBits(0);
6749 bool first = true;
6750 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6751 while (heapSize > 0) {
6752 if (first) {
6753 // The first time through the loop, we just consume the root element of
6754 // the heap (the one with smallest distance).
6755 first = false;
6756 } else {
6757 // Previous iterations consumed the root element of the heap.
6758 // Pop root element off of the heap (sift down).
6759 heap[0] = heap[heapSize];
6760 for (uint32_t parentIndex = 0; ;) {
6761 uint32_t childIndex = parentIndex * 2 + 1;
6762 if (childIndex >= heapSize) {
6763 break;
6764 }
6765
6766 if (childIndex + 1 < heapSize
6767 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6768 childIndex += 1;
6769 }
6770
6771 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6772 break;
6773 }
6774
6775 swap(heap[parentIndex], heap[childIndex]);
6776 parentIndex = childIndex;
6777 }
6778
6779#if DEBUG_POINTER_ASSIGNMENT
6780 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6781 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006782 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006783 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6784 heap[i].distance);
6785 }
6786#endif
6787 }
6788
6789 heapSize -= 1;
6790
6791 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6792 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6793
6794 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6795 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6796
6797 matchedCurrentBits.markBit(currentPointerIndex);
6798 matchedLastBits.markBit(lastPointerIndex);
6799
Michael Wright842500e2015-03-13 17:32:02 -07006800 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6801 current->rawPointerData.pointers[currentPointerIndex].id = id;
6802 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6803 current->rawPointerData.markIdBit(id,
6804 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006805 usedIdBits.markBit(id);
6806
6807#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006808 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6809 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006810 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6811#endif
6812 break;
6813 }
6814 }
6815
6816 // Assign fresh ids to pointers that were not matched in the process.
6817 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6818 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6819 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6820
Michael Wright842500e2015-03-13 17:32:02 -07006821 current->rawPointerData.pointers[currentPointerIndex].id = id;
6822 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6823 current->rawPointerData.markIdBit(id,
6824 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006825
6826#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006827 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006828#endif
6829 }
6830}
6831
6832int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6833 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6834 return AKEY_STATE_VIRTUAL;
6835 }
6836
6837 size_t numVirtualKeys = mVirtualKeys.size();
6838 for (size_t i = 0; i < numVirtualKeys; i++) {
6839 const VirtualKey& virtualKey = mVirtualKeys[i];
6840 if (virtualKey.keyCode == keyCode) {
6841 return AKEY_STATE_UP;
6842 }
6843 }
6844
6845 return AKEY_STATE_UNKNOWN;
6846}
6847
6848int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6849 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6850 return AKEY_STATE_VIRTUAL;
6851 }
6852
6853 size_t numVirtualKeys = mVirtualKeys.size();
6854 for (size_t i = 0; i < numVirtualKeys; i++) {
6855 const VirtualKey& virtualKey = mVirtualKeys[i];
6856 if (virtualKey.scanCode == scanCode) {
6857 return AKEY_STATE_UP;
6858 }
6859 }
6860
6861 return AKEY_STATE_UNKNOWN;
6862}
6863
6864bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6865 const int32_t* keyCodes, uint8_t* outFlags) {
6866 size_t numVirtualKeys = mVirtualKeys.size();
6867 for (size_t i = 0; i < numVirtualKeys; i++) {
6868 const VirtualKey& virtualKey = mVirtualKeys[i];
6869
6870 for (size_t i = 0; i < numCodes; i++) {
6871 if (virtualKey.keyCode == keyCodes[i]) {
6872 outFlags[i] = 1;
6873 }
6874 }
6875 }
6876
6877 return true;
6878}
6879
Arthur Hungc23540e2018-11-29 20:42:11 +08006880std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6881 if (mParameters.hasAssociatedDisplay) {
6882 if (mDeviceMode == DEVICE_MODE_POINTER) {
6883 return std::make_optional(mPointerController->getDisplayId());
6884 } else {
6885 return std::make_optional(mViewport.displayId);
6886 }
6887 }
6888 return std::nullopt;
6889}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006890
6891// --- SingleTouchInputMapper ---
6892
6893SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6894 TouchInputMapper(device) {
6895}
6896
6897SingleTouchInputMapper::~SingleTouchInputMapper() {
6898}
6899
6900void SingleTouchInputMapper::reset(nsecs_t when) {
6901 mSingleTouchMotionAccumulator.reset(getDevice());
6902
6903 TouchInputMapper::reset(when);
6904}
6905
6906void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6907 TouchInputMapper::process(rawEvent);
6908
6909 mSingleTouchMotionAccumulator.process(rawEvent);
6910}
6911
Michael Wright842500e2015-03-13 17:32:02 -07006912void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006913 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006914 outState->rawPointerData.pointerCount = 1;
6915 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006916
6917 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6918 && (mTouchButtonAccumulator.isHovering()
6919 || (mRawPointerAxes.pressure.valid
6920 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006921 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006922
Michael Wright842500e2015-03-13 17:32:02 -07006923 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006924 outPointer.id = 0;
6925 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6926 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6927 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6928 outPointer.touchMajor = 0;
6929 outPointer.touchMinor = 0;
6930 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6931 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6932 outPointer.orientation = 0;
6933 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6934 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6935 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6936 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6937 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6938 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6939 }
6940 outPointer.isHovering = isHovering;
6941 }
6942}
6943
6944void SingleTouchInputMapper::configureRawPointerAxes() {
6945 TouchInputMapper::configureRawPointerAxes();
6946
6947 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6948 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6949 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6950 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6951 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6952 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6953 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6954}
6955
6956bool SingleTouchInputMapper::hasStylus() const {
6957 return mTouchButtonAccumulator.hasStylus();
6958}
6959
6960
6961// --- MultiTouchInputMapper ---
6962
6963MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6964 TouchInputMapper(device) {
6965}
6966
6967MultiTouchInputMapper::~MultiTouchInputMapper() {
6968}
6969
6970void MultiTouchInputMapper::reset(nsecs_t when) {
6971 mMultiTouchMotionAccumulator.reset(getDevice());
6972
6973 mPointerIdBits.clear();
6974
6975 TouchInputMapper::reset(when);
6976}
6977
6978void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6979 TouchInputMapper::process(rawEvent);
6980
6981 mMultiTouchMotionAccumulator.process(rawEvent);
6982}
6983
Michael Wright842500e2015-03-13 17:32:02 -07006984void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006985 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6986 size_t outCount = 0;
6987 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006988 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006989
6990 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6991 const MultiTouchMotionAccumulator::Slot* inSlot =
6992 mMultiTouchMotionAccumulator.getSlot(inIndex);
6993 if (!inSlot->isInUse()) {
6994 continue;
6995 }
6996
6997 if (outCount >= MAX_POINTERS) {
6998#if DEBUG_POINTERS
6999 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
7000 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007001 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007002#endif
7003 break; // too many fingers!
7004 }
7005
Michael Wright842500e2015-03-13 17:32:02 -07007006 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08007007 outPointer.x = inSlot->getX();
7008 outPointer.y = inSlot->getY();
7009 outPointer.pressure = inSlot->getPressure();
7010 outPointer.touchMajor = inSlot->getTouchMajor();
7011 outPointer.touchMinor = inSlot->getTouchMinor();
7012 outPointer.toolMajor = inSlot->getToolMajor();
7013 outPointer.toolMinor = inSlot->getToolMinor();
7014 outPointer.orientation = inSlot->getOrientation();
7015 outPointer.distance = inSlot->getDistance();
7016 outPointer.tiltX = 0;
7017 outPointer.tiltY = 0;
7018
7019 outPointer.toolType = inSlot->getToolType();
7020 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7021 outPointer.toolType = mTouchButtonAccumulator.getToolType();
7022 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7023 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
7024 }
7025 }
7026
7027 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
7028 && (mTouchButtonAccumulator.isHovering()
7029 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
7030 outPointer.isHovering = isHovering;
7031
7032 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08007033 if (mHavePointerIds) {
7034 int32_t trackingId = inSlot->getTrackingId();
7035 int32_t id = -1;
7036 if (trackingId >= 0) {
7037 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
7038 uint32_t n = idBits.clearFirstMarkedBit();
7039 if (mPointerTrackingIdMap[n] == trackingId) {
7040 id = n;
7041 }
7042 }
7043
7044 if (id < 0 && !mPointerIdBits.isFull()) {
7045 id = mPointerIdBits.markFirstUnmarkedBit();
7046 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007047 }
Michael Wright842500e2015-03-13 17:32:02 -07007048 }
gaoshang1a632de2016-08-24 10:23:50 +08007049 if (id < 0) {
7050 mHavePointerIds = false;
7051 outState->rawPointerData.clearIdBits();
7052 newPointerIdBits.clear();
7053 } else {
7054 outPointer.id = id;
7055 outState->rawPointerData.idToIndex[id] = outCount;
7056 outState->rawPointerData.markIdBit(id, isHovering);
7057 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007058 }
Michael Wright842500e2015-03-13 17:32:02 -07007059 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007060 outCount += 1;
7061 }
7062
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007063 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007064 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007065 mPointerIdBits = newPointerIdBits;
7066
7067 mMultiTouchMotionAccumulator.finishSync();
7068}
7069
7070void MultiTouchInputMapper::configureRawPointerAxes() {
7071 TouchInputMapper::configureRawPointerAxes();
7072
7073 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7074 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7075 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7076 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7077 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7078 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7079 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7080 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7081 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7082 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7083 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7084
7085 if (mRawPointerAxes.trackingId.valid
7086 && mRawPointerAxes.slot.valid
7087 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7088 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7089 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007090 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7091 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007092 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007093 slotCount = MAX_SLOTS;
7094 }
7095 mMultiTouchMotionAccumulator.configure(getDevice(),
7096 slotCount, true /*usingSlotsProtocol*/);
7097 } else {
7098 mMultiTouchMotionAccumulator.configure(getDevice(),
7099 MAX_POINTERS, false /*usingSlotsProtocol*/);
7100 }
7101}
7102
7103bool MultiTouchInputMapper::hasStylus() const {
7104 return mMultiTouchMotionAccumulator.hasStylus()
7105 || mTouchButtonAccumulator.hasStylus();
7106}
7107
Michael Wright842500e2015-03-13 17:32:02 -07007108// --- ExternalStylusInputMapper
7109
7110ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7111 InputMapper(device) {
7112
7113}
7114
7115uint32_t ExternalStylusInputMapper::getSources() {
7116 return AINPUT_SOURCE_STYLUS;
7117}
7118
7119void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7120 InputMapper::populateDeviceInfo(info);
7121 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7122 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7123}
7124
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007125void ExternalStylusInputMapper::dump(std::string& dump) {
7126 dump += INDENT2 "External Stylus Input Mapper:\n";
7127 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007128 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007129 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007130 dumpStylusState(dump, mStylusState);
7131}
7132
7133void ExternalStylusInputMapper::configure(nsecs_t when,
7134 const InputReaderConfiguration* config, uint32_t changes) {
7135 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7136 mTouchButtonAccumulator.configure(getDevice());
7137}
7138
7139void ExternalStylusInputMapper::reset(nsecs_t when) {
7140 InputDevice* device = getDevice();
7141 mSingleTouchMotionAccumulator.reset(device);
7142 mTouchButtonAccumulator.reset(device);
7143 InputMapper::reset(when);
7144}
7145
7146void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7147 mSingleTouchMotionAccumulator.process(rawEvent);
7148 mTouchButtonAccumulator.process(rawEvent);
7149
7150 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7151 sync(rawEvent->when);
7152 }
7153}
7154
7155void ExternalStylusInputMapper::sync(nsecs_t when) {
7156 mStylusState.clear();
7157
7158 mStylusState.when = when;
7159
Michael Wright45ccacf2015-04-21 19:01:58 +01007160 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7161 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7162 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7163 }
7164
Michael Wright842500e2015-03-13 17:32:02 -07007165 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7166 if (mRawPressureAxis.valid) {
7167 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7168 } else if (mTouchButtonAccumulator.isToolActive()) {
7169 mStylusState.pressure = 1.0f;
7170 } else {
7171 mStylusState.pressure = 0.0f;
7172 }
7173
7174 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007175
7176 mContext->dispatchExternalStylusState(mStylusState);
7177}
7178
Michael Wrightd02c5b62014-02-10 15:10:22 -08007179
7180// --- JoystickInputMapper ---
7181
7182JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7183 InputMapper(device) {
7184}
7185
7186JoystickInputMapper::~JoystickInputMapper() {
7187}
7188
7189uint32_t JoystickInputMapper::getSources() {
7190 return AINPUT_SOURCE_JOYSTICK;
7191}
7192
7193void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7194 InputMapper::populateDeviceInfo(info);
7195
7196 for (size_t i = 0; i < mAxes.size(); i++) {
7197 const Axis& axis = mAxes.valueAt(i);
7198 addMotionRange(axis.axisInfo.axis, axis, info);
7199
7200 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7201 addMotionRange(axis.axisInfo.highAxis, axis, info);
7202
7203 }
7204 }
7205}
7206
7207void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7208 InputDeviceInfo* info) {
7209 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7210 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7211 /* In order to ease the transition for developers from using the old axes
7212 * to the newer, more semantically correct axes, we'll continue to register
7213 * the old axes as duplicates of their corresponding new ones. */
7214 int32_t compatAxis = getCompatAxis(axisId);
7215 if (compatAxis >= 0) {
7216 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7217 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7218 }
7219}
7220
7221/* A mapping from axes the joystick actually has to the axes that should be
7222 * artificially created for compatibility purposes.
7223 * Returns -1 if no compatibility axis is needed. */
7224int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7225 switch(axis) {
7226 case AMOTION_EVENT_AXIS_LTRIGGER:
7227 return AMOTION_EVENT_AXIS_BRAKE;
7228 case AMOTION_EVENT_AXIS_RTRIGGER:
7229 return AMOTION_EVENT_AXIS_GAS;
7230 }
7231 return -1;
7232}
7233
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007234void JoystickInputMapper::dump(std::string& dump) {
7235 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007236
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007237 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007238 size_t numAxes = mAxes.size();
7239 for (size_t i = 0; i < numAxes; i++) {
7240 const Axis& axis = mAxes.valueAt(i);
7241 const char* label = getAxisLabel(axis.axisInfo.axis);
7242 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007243 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007244 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007245 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007246 }
7247 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7248 label = getAxisLabel(axis.axisInfo.highAxis);
7249 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007250 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007251 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007252 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007253 axis.axisInfo.splitValue);
7254 }
7255 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007256 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007257 }
7258
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007259 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 -08007260 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007261 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007262 "highScale=%0.5f, highOffset=%0.5f\n",
7263 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007264 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007265 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7266 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7267 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7268 }
7269}
7270
7271void JoystickInputMapper::configure(nsecs_t when,
7272 const InputReaderConfiguration* config, uint32_t changes) {
7273 InputMapper::configure(when, config, changes);
7274
7275 if (!changes) { // first time only
7276 // Collect all axes.
7277 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7278 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7279 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7280 continue; // axis must be claimed by a different device
7281 }
7282
7283 RawAbsoluteAxisInfo rawAxisInfo;
7284 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7285 if (rawAxisInfo.valid) {
7286 // Map axis.
7287 AxisInfo axisInfo;
7288 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7289 if (!explicitlyMapped) {
7290 // Axis is not explicitly mapped, will choose a generic axis later.
7291 axisInfo.mode = AxisInfo::MODE_NORMAL;
7292 axisInfo.axis = -1;
7293 }
7294
7295 // Apply flat override.
7296 int32_t rawFlat = axisInfo.flatOverride < 0
7297 ? rawAxisInfo.flat : axisInfo.flatOverride;
7298
7299 // Calculate scaling factors and limits.
7300 Axis axis;
7301 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7302 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7303 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7304 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7305 scale, 0.0f, highScale, 0.0f,
7306 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7307 rawAxisInfo.resolution * scale);
7308 } else if (isCenteredAxis(axisInfo.axis)) {
7309 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7310 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7311 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7312 scale, offset, scale, offset,
7313 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7314 rawAxisInfo.resolution * scale);
7315 } else {
7316 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7317 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7318 scale, 0.0f, scale, 0.0f,
7319 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7320 rawAxisInfo.resolution * scale);
7321 }
7322
7323 // To eliminate noise while the joystick is at rest, filter out small variations
7324 // in axis values up front.
7325 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7326
7327 mAxes.add(abs, axis);
7328 }
7329 }
7330
7331 // If there are too many axes, start dropping them.
7332 // Prefer to keep explicitly mapped axes.
7333 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007334 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007335 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007336 pruneAxes(true);
7337 pruneAxes(false);
7338 }
7339
7340 // Assign generic axis ids to remaining axes.
7341 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7342 size_t numAxes = mAxes.size();
7343 for (size_t i = 0; i < numAxes; i++) {
7344 Axis& axis = mAxes.editValueAt(i);
7345 if (axis.axisInfo.axis < 0) {
7346 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7347 && haveAxis(nextGenericAxisId)) {
7348 nextGenericAxisId += 1;
7349 }
7350
7351 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7352 axis.axisInfo.axis = nextGenericAxisId;
7353 nextGenericAxisId += 1;
7354 } else {
7355 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7356 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007357 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007358 mAxes.removeItemsAt(i--);
7359 numAxes -= 1;
7360 }
7361 }
7362 }
7363 }
7364}
7365
7366bool JoystickInputMapper::haveAxis(int32_t axisId) {
7367 size_t numAxes = mAxes.size();
7368 for (size_t i = 0; i < numAxes; i++) {
7369 const Axis& axis = mAxes.valueAt(i);
7370 if (axis.axisInfo.axis == axisId
7371 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7372 && axis.axisInfo.highAxis == axisId)) {
7373 return true;
7374 }
7375 }
7376 return false;
7377}
7378
7379void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7380 size_t i = mAxes.size();
7381 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7382 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7383 continue;
7384 }
7385 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007386 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007387 mAxes.removeItemsAt(i);
7388 }
7389}
7390
7391bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7392 switch (axis) {
7393 case AMOTION_EVENT_AXIS_X:
7394 case AMOTION_EVENT_AXIS_Y:
7395 case AMOTION_EVENT_AXIS_Z:
7396 case AMOTION_EVENT_AXIS_RX:
7397 case AMOTION_EVENT_AXIS_RY:
7398 case AMOTION_EVENT_AXIS_RZ:
7399 case AMOTION_EVENT_AXIS_HAT_X:
7400 case AMOTION_EVENT_AXIS_HAT_Y:
7401 case AMOTION_EVENT_AXIS_ORIENTATION:
7402 case AMOTION_EVENT_AXIS_RUDDER:
7403 case AMOTION_EVENT_AXIS_WHEEL:
7404 return true;
7405 default:
7406 return false;
7407 }
7408}
7409
7410void JoystickInputMapper::reset(nsecs_t when) {
7411 // Recenter all axes.
7412 size_t numAxes = mAxes.size();
7413 for (size_t i = 0; i < numAxes; i++) {
7414 Axis& axis = mAxes.editValueAt(i);
7415 axis.resetValue();
7416 }
7417
7418 InputMapper::reset(when);
7419}
7420
7421void JoystickInputMapper::process(const RawEvent* rawEvent) {
7422 switch (rawEvent->type) {
7423 case EV_ABS: {
7424 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7425 if (index >= 0) {
7426 Axis& axis = mAxes.editValueAt(index);
7427 float newValue, highNewValue;
7428 switch (axis.axisInfo.mode) {
7429 case AxisInfo::MODE_INVERT:
7430 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7431 * axis.scale + axis.offset;
7432 highNewValue = 0.0f;
7433 break;
7434 case AxisInfo::MODE_SPLIT:
7435 if (rawEvent->value < axis.axisInfo.splitValue) {
7436 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7437 * axis.scale + axis.offset;
7438 highNewValue = 0.0f;
7439 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7440 newValue = 0.0f;
7441 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7442 * axis.highScale + axis.highOffset;
7443 } else {
7444 newValue = 0.0f;
7445 highNewValue = 0.0f;
7446 }
7447 break;
7448 default:
7449 newValue = rawEvent->value * axis.scale + axis.offset;
7450 highNewValue = 0.0f;
7451 break;
7452 }
7453 axis.newValue = newValue;
7454 axis.highNewValue = highNewValue;
7455 }
7456 break;
7457 }
7458
7459 case EV_SYN:
7460 switch (rawEvent->code) {
7461 case SYN_REPORT:
7462 sync(rawEvent->when, false /*force*/);
7463 break;
7464 }
7465 break;
7466 }
7467}
7468
7469void JoystickInputMapper::sync(nsecs_t when, bool force) {
7470 if (!filterAxes(force)) {
7471 return;
7472 }
7473
7474 int32_t metaState = mContext->getGlobalMetaState();
7475 int32_t buttonState = 0;
7476
7477 PointerProperties pointerProperties;
7478 pointerProperties.clear();
7479 pointerProperties.id = 0;
7480 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7481
7482 PointerCoords pointerCoords;
7483 pointerCoords.clear();
7484
7485 size_t numAxes = mAxes.size();
7486 for (size_t i = 0; i < numAxes; i++) {
7487 const Axis& axis = mAxes.valueAt(i);
7488 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7489 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7490 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7491 axis.highCurrentValue);
7492 }
7493 }
7494
7495 // Moving a joystick axis should not wake the device because joysticks can
7496 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7497 // button will likely wake the device.
7498 // TODO: Use the input device configuration to control this behavior more finely.
7499 uint32_t policyFlags = 0;
7500
Prabir Pradhan42611e02018-11-27 14:04:02 -08007501 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7502 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007503 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7504 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7505 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007506 getListener()->notifyMotion(&args);
7507}
7508
7509void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7510 int32_t axis, float value) {
7511 pointerCoords->setAxisValue(axis, value);
7512 /* In order to ease the transition for developers from using the old axes
7513 * to the newer, more semantically correct axes, we'll continue to produce
7514 * values for the old axes as mirrors of the value of their corresponding
7515 * new axes. */
7516 int32_t compatAxis = getCompatAxis(axis);
7517 if (compatAxis >= 0) {
7518 pointerCoords->setAxisValue(compatAxis, value);
7519 }
7520}
7521
7522bool JoystickInputMapper::filterAxes(bool force) {
7523 bool atLeastOneSignificantChange = force;
7524 size_t numAxes = mAxes.size();
7525 for (size_t i = 0; i < numAxes; i++) {
7526 Axis& axis = mAxes.editValueAt(i);
7527 if (force || hasValueChangedSignificantly(axis.filter,
7528 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7529 axis.currentValue = axis.newValue;
7530 atLeastOneSignificantChange = true;
7531 }
7532 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7533 if (force || hasValueChangedSignificantly(axis.filter,
7534 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7535 axis.highCurrentValue = axis.highNewValue;
7536 atLeastOneSignificantChange = true;
7537 }
7538 }
7539 }
7540 return atLeastOneSignificantChange;
7541}
7542
7543bool JoystickInputMapper::hasValueChangedSignificantly(
7544 float filter, float newValue, float currentValue, float min, float max) {
7545 if (newValue != currentValue) {
7546 // Filter out small changes in value unless the value is converging on the axis
7547 // bounds or center point. This is intended to reduce the amount of information
7548 // sent to applications by particularly noisy joysticks (such as PS3).
7549 if (fabs(newValue - currentValue) > filter
7550 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7551 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7552 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7553 return true;
7554 }
7555 }
7556 return false;
7557}
7558
7559bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7560 float filter, float newValue, float currentValue, float thresholdValue) {
7561 float newDistance = fabs(newValue - thresholdValue);
7562 if (newDistance < filter) {
7563 float oldDistance = fabs(currentValue - thresholdValue);
7564 if (newDistance < oldDistance) {
7565 return true;
7566 }
7567 }
7568 return false;
7569}
7570
7571} // namespace android