blob: 68983a907c7f3ba3a8fd19bd2cca0697ef71fdef [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
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800808void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809 AutoMutex _l(mLock);
810
811 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800812 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800813
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800814 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800815
816 for (size_t i = 0; i < mDevices.size(); i++) {
817 mDevices.valueAt(i)->dump(dump);
818 }
819
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800820 dump += INDENT "Configuration:\n";
821 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
823 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800824 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800825 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100826 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800828 dump += "]\n";
829 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 mConfig.virtualKeyQuietTime * 0.000001f);
831
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800832 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800833 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
834 mConfig.pointerVelocityControlParameters.scale,
835 mConfig.pointerVelocityControlParameters.lowThreshold,
836 mConfig.pointerVelocityControlParameters.highThreshold,
837 mConfig.pointerVelocityControlParameters.acceleration);
838
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800839 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800840 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
841 mConfig.wheelVelocityControlParameters.scale,
842 mConfig.wheelVelocityControlParameters.lowThreshold,
843 mConfig.wheelVelocityControlParameters.highThreshold,
844 mConfig.wheelVelocityControlParameters.acceleration);
845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += StringPrintf(INDENT2 "PointerGesture:\n");
847 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800849 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800851 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800853 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800855 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800857 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800859 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800861 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800863 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800867 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800868 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800869 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700871
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800872 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700873 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800874}
875
876void InputReader::monitor() {
877 // Acquire and release the lock to ensure that the reader has not deadlocked.
878 mLock.lock();
879 mEventHub->wake();
880 mReaderIsAliveCondition.wait(mLock);
881 mLock.unlock();
882
883 // Check the EventHub
884 mEventHub->monitor();
885}
886
887
888// --- InputReader::ContextImpl ---
889
890InputReader::ContextImpl::ContextImpl(InputReader* reader) :
891 mReader(reader) {
892}
893
894void InputReader::ContextImpl::updateGlobalMetaState() {
895 // lock is already held by the input loop
896 mReader->updateGlobalMetaStateLocked();
897}
898
899int32_t InputReader::ContextImpl::getGlobalMetaState() {
900 // lock is already held by the input loop
901 return mReader->getGlobalMetaStateLocked();
902}
903
904void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
905 // lock is already held by the input loop
906 mReader->disableVirtualKeysUntilLocked(time);
907}
908
909bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
910 InputDevice* device, int32_t keyCode, int32_t scanCode) {
911 // lock is already held by the input loop
912 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
913}
914
915void InputReader::ContextImpl::fadePointer() {
916 // lock is already held by the input loop
917 mReader->fadePointerLocked();
918}
919
920void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
921 // lock is already held by the input loop
922 mReader->requestTimeoutAtTimeLocked(when);
923}
924
925int32_t InputReader::ContextImpl::bumpGeneration() {
926 // lock is already held by the input loop
927 return mReader->bumpGenerationLocked();
928}
929
Michael Wright842500e2015-03-13 17:32:02 -0700930void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
931 // lock is already held by whatever called refreshConfigurationLocked
932 mReader->getExternalStylusDevicesLocked(outDevices);
933}
934
935void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
936 mReader->dispatchExternalStylusState(state);
937}
938
Michael Wrightd02c5b62014-02-10 15:10:22 -0800939InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
940 return mReader->mPolicy.get();
941}
942
943InputListenerInterface* InputReader::ContextImpl::getListener() {
944 return mReader->mQueuedListener.get();
945}
946
947EventHubInterface* InputReader::ContextImpl::getEventHub() {
948 return mReader->mEventHub.get();
949}
950
Prabir Pradhan42611e02018-11-27 14:04:02 -0800951uint32_t InputReader::ContextImpl::getNextSequenceNum() {
952 return (mReader->mNextSequenceNum)++;
953}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800954
Michael Wrightd02c5b62014-02-10 15:10:22 -0800955// --- InputDevice ---
956
957InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
958 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
959 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
960 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700961 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800962}
963
964InputDevice::~InputDevice() {
965 size_t numMappers = mMappers.size();
966 for (size_t i = 0; i < numMappers; i++) {
967 delete mMappers[i];
968 }
969 mMappers.clear();
970}
971
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700972bool InputDevice::isEnabled() {
973 return getEventHub()->isDeviceEnabled(mId);
974}
975
976void InputDevice::setEnabled(bool enabled, nsecs_t when) {
977 if (isEnabled() == enabled) {
978 return;
979 }
980
981 if (enabled) {
982 getEventHub()->enableDevice(mId);
983 reset(when);
984 } else {
985 reset(when);
986 getEventHub()->disableDevice(mId);
987 }
988 // Must change generation to flag this device as changed
989 bumpGeneration();
990}
991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800993 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700994 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800995
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800996 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100997 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800998 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
999 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001000 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1001 if (mAssociatedDisplayPort) {
1002 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1003 } else {
1004 dump += "<none>\n";
1005 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001006 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1007 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1008 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009
1010 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1011 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001012 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001013 for (size_t i = 0; i < ranges.size(); i++) {
1014 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1015 const char* label = getAxisLabel(range.axis);
1016 char name[32];
1017 if (label) {
1018 strncpy(name, label, sizeof(name));
1019 name[sizeof(name) - 1] = '\0';
1020 } else {
1021 snprintf(name, sizeof(name), "%d", range.axis);
1022 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001023 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001024 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1025 name, range.source, range.min, range.max, range.flat, range.fuzz,
1026 range.resolution);
1027 }
1028 }
1029
1030 size_t numMappers = mMappers.size();
1031 for (size_t i = 0; i < numMappers; i++) {
1032 InputMapper* mapper = mMappers[i];
1033 mapper->dump(dump);
1034 }
1035}
1036
1037void InputDevice::addMapper(InputMapper* mapper) {
1038 mMappers.add(mapper);
1039}
1040
1041void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1042 mSources = 0;
1043
1044 if (!isIgnored()) {
1045 if (!changes) { // first time only
1046 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1047 }
1048
1049 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1050 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1051 sp<KeyCharacterMap> keyboardLayout =
1052 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1053 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1054 bumpGeneration();
1055 }
1056 }
1057 }
1058
1059 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1060 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001061 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001062 if (mAlias != alias) {
1063 mAlias = alias;
1064 bumpGeneration();
1065 }
1066 }
1067 }
1068
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001069 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1070 ssize_t index = config->disabledDevices.indexOf(mId);
1071 bool enabled = index < 0;
1072 setEnabled(enabled, when);
1073 }
1074
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001075 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1076 // In most situations, no port will be specified.
1077 mAssociatedDisplayPort = std::nullopt;
1078 // Find the display port that corresponds to the current input port.
1079 const std::string& inputPort = mIdentifier.location;
1080 if (!inputPort.empty()) {
1081 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1082 const auto& displayPort = ports.find(inputPort);
1083 if (displayPort != ports.end()) {
1084 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1085 }
1086 }
1087 }
1088
Michael Wrightd02c5b62014-02-10 15:10:22 -08001089 size_t numMappers = mMappers.size();
1090 for (size_t i = 0; i < numMappers; i++) {
1091 InputMapper* mapper = mMappers[i];
1092 mapper->configure(when, config, changes);
1093 mSources |= mapper->getSources();
1094 }
1095 }
1096}
1097
1098void InputDevice::reset(nsecs_t when) {
1099 size_t numMappers = mMappers.size();
1100 for (size_t i = 0; i < numMappers; i++) {
1101 InputMapper* mapper = mMappers[i];
1102 mapper->reset(when);
1103 }
1104
1105 mContext->updateGlobalMetaState();
1106
1107 notifyReset(when);
1108}
1109
1110void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1111 // Process all of the events in order for each mapper.
1112 // We cannot simply ask each mapper to process them in bulk because mappers may
1113 // have side-effects that must be interleaved. For example, joystick movement events and
1114 // gamepad button presses are handled by different mappers but they should be dispatched
1115 // in the order received.
1116 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001117 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001118#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001119 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1121 rawEvent->when);
1122#endif
1123
1124 if (mDropUntilNextSync) {
1125 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1126 mDropUntilNextSync = false;
1127#if DEBUG_RAW_EVENTS
1128 ALOGD("Recovered from input event buffer overrun.");
1129#endif
1130 } else {
1131#if DEBUG_RAW_EVENTS
1132 ALOGD("Dropped input event while waiting for next input sync.");
1133#endif
1134 }
1135 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001136 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001137 mDropUntilNextSync = true;
1138 reset(rawEvent->when);
1139 } else {
1140 for (size_t i = 0; i < numMappers; i++) {
1141 InputMapper* mapper = mMappers[i];
1142 mapper->process(rawEvent);
1143 }
1144 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001145 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001146 }
1147}
1148
1149void InputDevice::timeoutExpired(nsecs_t when) {
1150 size_t numMappers = mMappers.size();
1151 for (size_t i = 0; i < numMappers; i++) {
1152 InputMapper* mapper = mMappers[i];
1153 mapper->timeoutExpired(when);
1154 }
1155}
1156
Michael Wright842500e2015-03-13 17:32:02 -07001157void InputDevice::updateExternalStylusState(const StylusState& state) {
1158 size_t numMappers = mMappers.size();
1159 for (size_t i = 0; i < numMappers; i++) {
1160 InputMapper* mapper = mMappers[i];
1161 mapper->updateExternalStylusState(state);
1162 }
1163}
1164
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1166 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001167 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 size_t numMappers = mMappers.size();
1169 for (size_t i = 0; i < numMappers; i++) {
1170 InputMapper* mapper = mMappers[i];
1171 mapper->populateDeviceInfo(outDeviceInfo);
1172 }
1173}
1174
1175int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1176 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1177}
1178
1179int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1180 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1181}
1182
1183int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1184 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1185}
1186
1187int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1188 int32_t result = AKEY_STATE_UNKNOWN;
1189 size_t numMappers = mMappers.size();
1190 for (size_t i = 0; i < numMappers; i++) {
1191 InputMapper* mapper = mMappers[i];
1192 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1193 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1194 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1195 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1196 if (currentResult >= AKEY_STATE_DOWN) {
1197 return currentResult;
1198 } else if (currentResult == AKEY_STATE_UP) {
1199 result = currentResult;
1200 }
1201 }
1202 }
1203 return result;
1204}
1205
1206bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1207 const int32_t* keyCodes, uint8_t* outFlags) {
1208 bool result = false;
1209 size_t numMappers = mMappers.size();
1210 for (size_t i = 0; i < numMappers; i++) {
1211 InputMapper* mapper = mMappers[i];
1212 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1213 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1214 }
1215 }
1216 return result;
1217}
1218
1219void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1220 int32_t token) {
1221 size_t numMappers = mMappers.size();
1222 for (size_t i = 0; i < numMappers; i++) {
1223 InputMapper* mapper = mMappers[i];
1224 mapper->vibrate(pattern, patternSize, repeat, token);
1225 }
1226}
1227
1228void InputDevice::cancelVibrate(int32_t token) {
1229 size_t numMappers = mMappers.size();
1230 for (size_t i = 0; i < numMappers; i++) {
1231 InputMapper* mapper = mMappers[i];
1232 mapper->cancelVibrate(token);
1233 }
1234}
1235
Jeff Brownc9aa6282015-02-11 19:03:28 -08001236void InputDevice::cancelTouch(nsecs_t when) {
1237 size_t numMappers = mMappers.size();
1238 for (size_t i = 0; i < numMappers; i++) {
1239 InputMapper* mapper = mMappers[i];
1240 mapper->cancelTouch(when);
1241 }
1242}
1243
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244int32_t InputDevice::getMetaState() {
1245 int32_t result = 0;
1246 size_t numMappers = mMappers.size();
1247 for (size_t i = 0; i < numMappers; i++) {
1248 InputMapper* mapper = mMappers[i];
1249 result |= mapper->getMetaState();
1250 }
1251 return result;
1252}
1253
Andrii Kulian763a3a42016-03-08 10:46:16 -08001254void InputDevice::updateMetaState(int32_t keyCode) {
1255 size_t numMappers = mMappers.size();
1256 for (size_t i = 0; i < numMappers; i++) {
1257 mMappers[i]->updateMetaState(keyCode);
1258 }
1259}
1260
Michael Wrightd02c5b62014-02-10 15:10:22 -08001261void InputDevice::fadePointer() {
1262 size_t numMappers = mMappers.size();
1263 for (size_t i = 0; i < numMappers; i++) {
1264 InputMapper* mapper = mMappers[i];
1265 mapper->fadePointer();
1266 }
1267}
1268
1269void InputDevice::bumpGeneration() {
1270 mGeneration = mContext->bumpGeneration();
1271}
1272
1273void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001274 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001275 mContext->getListener()->notifyDeviceReset(&args);
1276}
1277
1278
1279// --- CursorButtonAccumulator ---
1280
1281CursorButtonAccumulator::CursorButtonAccumulator() {
1282 clearButtons();
1283}
1284
1285void CursorButtonAccumulator::reset(InputDevice* device) {
1286 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1287 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1288 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1289 mBtnBack = device->isKeyPressed(BTN_BACK);
1290 mBtnSide = device->isKeyPressed(BTN_SIDE);
1291 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1292 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1293 mBtnTask = device->isKeyPressed(BTN_TASK);
1294}
1295
1296void CursorButtonAccumulator::clearButtons() {
1297 mBtnLeft = 0;
1298 mBtnRight = 0;
1299 mBtnMiddle = 0;
1300 mBtnBack = 0;
1301 mBtnSide = 0;
1302 mBtnForward = 0;
1303 mBtnExtra = 0;
1304 mBtnTask = 0;
1305}
1306
1307void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1308 if (rawEvent->type == EV_KEY) {
1309 switch (rawEvent->code) {
1310 case BTN_LEFT:
1311 mBtnLeft = rawEvent->value;
1312 break;
1313 case BTN_RIGHT:
1314 mBtnRight = rawEvent->value;
1315 break;
1316 case BTN_MIDDLE:
1317 mBtnMiddle = rawEvent->value;
1318 break;
1319 case BTN_BACK:
1320 mBtnBack = rawEvent->value;
1321 break;
1322 case BTN_SIDE:
1323 mBtnSide = rawEvent->value;
1324 break;
1325 case BTN_FORWARD:
1326 mBtnForward = rawEvent->value;
1327 break;
1328 case BTN_EXTRA:
1329 mBtnExtra = rawEvent->value;
1330 break;
1331 case BTN_TASK:
1332 mBtnTask = rawEvent->value;
1333 break;
1334 }
1335 }
1336}
1337
1338uint32_t CursorButtonAccumulator::getButtonState() const {
1339 uint32_t result = 0;
1340 if (mBtnLeft) {
1341 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1342 }
1343 if (mBtnRight) {
1344 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1345 }
1346 if (mBtnMiddle) {
1347 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1348 }
1349 if (mBtnBack || mBtnSide) {
1350 result |= AMOTION_EVENT_BUTTON_BACK;
1351 }
1352 if (mBtnForward || mBtnExtra) {
1353 result |= AMOTION_EVENT_BUTTON_FORWARD;
1354 }
1355 return result;
1356}
1357
1358
1359// --- CursorMotionAccumulator ---
1360
1361CursorMotionAccumulator::CursorMotionAccumulator() {
1362 clearRelativeAxes();
1363}
1364
1365void CursorMotionAccumulator::reset(InputDevice* device) {
1366 clearRelativeAxes();
1367}
1368
1369void CursorMotionAccumulator::clearRelativeAxes() {
1370 mRelX = 0;
1371 mRelY = 0;
1372}
1373
1374void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1375 if (rawEvent->type == EV_REL) {
1376 switch (rawEvent->code) {
1377 case REL_X:
1378 mRelX = rawEvent->value;
1379 break;
1380 case REL_Y:
1381 mRelY = rawEvent->value;
1382 break;
1383 }
1384 }
1385}
1386
1387void CursorMotionAccumulator::finishSync() {
1388 clearRelativeAxes();
1389}
1390
1391
1392// --- CursorScrollAccumulator ---
1393
1394CursorScrollAccumulator::CursorScrollAccumulator() :
1395 mHaveRelWheel(false), mHaveRelHWheel(false) {
1396 clearRelativeAxes();
1397}
1398
1399void CursorScrollAccumulator::configure(InputDevice* device) {
1400 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1401 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1402}
1403
1404void CursorScrollAccumulator::reset(InputDevice* device) {
1405 clearRelativeAxes();
1406}
1407
1408void CursorScrollAccumulator::clearRelativeAxes() {
1409 mRelWheel = 0;
1410 mRelHWheel = 0;
1411}
1412
1413void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1414 if (rawEvent->type == EV_REL) {
1415 switch (rawEvent->code) {
1416 case REL_WHEEL:
1417 mRelWheel = rawEvent->value;
1418 break;
1419 case REL_HWHEEL:
1420 mRelHWheel = rawEvent->value;
1421 break;
1422 }
1423 }
1424}
1425
1426void CursorScrollAccumulator::finishSync() {
1427 clearRelativeAxes();
1428}
1429
1430
1431// --- TouchButtonAccumulator ---
1432
1433TouchButtonAccumulator::TouchButtonAccumulator() :
1434 mHaveBtnTouch(false), mHaveStylus(false) {
1435 clearButtons();
1436}
1437
1438void TouchButtonAccumulator::configure(InputDevice* device) {
1439 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1440 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1441 || device->hasKey(BTN_TOOL_RUBBER)
1442 || device->hasKey(BTN_TOOL_BRUSH)
1443 || device->hasKey(BTN_TOOL_PENCIL)
1444 || device->hasKey(BTN_TOOL_AIRBRUSH);
1445}
1446
1447void TouchButtonAccumulator::reset(InputDevice* device) {
1448 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1449 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001450 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1451 mBtnStylus2 =
1452 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001453 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1454 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1455 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1456 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1457 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1458 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1459 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1460 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1461 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1462 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1463 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1464}
1465
1466void TouchButtonAccumulator::clearButtons() {
1467 mBtnTouch = 0;
1468 mBtnStylus = 0;
1469 mBtnStylus2 = 0;
1470 mBtnToolFinger = 0;
1471 mBtnToolPen = 0;
1472 mBtnToolRubber = 0;
1473 mBtnToolBrush = 0;
1474 mBtnToolPencil = 0;
1475 mBtnToolAirbrush = 0;
1476 mBtnToolMouse = 0;
1477 mBtnToolLens = 0;
1478 mBtnToolDoubleTap = 0;
1479 mBtnToolTripleTap = 0;
1480 mBtnToolQuadTap = 0;
1481}
1482
1483void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1484 if (rawEvent->type == EV_KEY) {
1485 switch (rawEvent->code) {
1486 case BTN_TOUCH:
1487 mBtnTouch = rawEvent->value;
1488 break;
1489 case BTN_STYLUS:
1490 mBtnStylus = rawEvent->value;
1491 break;
1492 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001493 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001494 mBtnStylus2 = rawEvent->value;
1495 break;
1496 case BTN_TOOL_FINGER:
1497 mBtnToolFinger = rawEvent->value;
1498 break;
1499 case BTN_TOOL_PEN:
1500 mBtnToolPen = rawEvent->value;
1501 break;
1502 case BTN_TOOL_RUBBER:
1503 mBtnToolRubber = rawEvent->value;
1504 break;
1505 case BTN_TOOL_BRUSH:
1506 mBtnToolBrush = rawEvent->value;
1507 break;
1508 case BTN_TOOL_PENCIL:
1509 mBtnToolPencil = rawEvent->value;
1510 break;
1511 case BTN_TOOL_AIRBRUSH:
1512 mBtnToolAirbrush = rawEvent->value;
1513 break;
1514 case BTN_TOOL_MOUSE:
1515 mBtnToolMouse = rawEvent->value;
1516 break;
1517 case BTN_TOOL_LENS:
1518 mBtnToolLens = rawEvent->value;
1519 break;
1520 case BTN_TOOL_DOUBLETAP:
1521 mBtnToolDoubleTap = rawEvent->value;
1522 break;
1523 case BTN_TOOL_TRIPLETAP:
1524 mBtnToolTripleTap = rawEvent->value;
1525 break;
1526 case BTN_TOOL_QUADTAP:
1527 mBtnToolQuadTap = rawEvent->value;
1528 break;
1529 }
1530 }
1531}
1532
1533uint32_t TouchButtonAccumulator::getButtonState() const {
1534 uint32_t result = 0;
1535 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001536 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001539 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001540 }
1541 return result;
1542}
1543
1544int32_t TouchButtonAccumulator::getToolType() const {
1545 if (mBtnToolMouse || mBtnToolLens) {
1546 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1547 }
1548 if (mBtnToolRubber) {
1549 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1550 }
1551 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1552 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1553 }
1554 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1555 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1556 }
1557 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1558}
1559
1560bool TouchButtonAccumulator::isToolActive() const {
1561 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1562 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1563 || mBtnToolMouse || mBtnToolLens
1564 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1565}
1566
1567bool TouchButtonAccumulator::isHovering() const {
1568 return mHaveBtnTouch && !mBtnTouch;
1569}
1570
1571bool TouchButtonAccumulator::hasStylus() const {
1572 return mHaveStylus;
1573}
1574
1575
1576// --- RawPointerAxes ---
1577
1578RawPointerAxes::RawPointerAxes() {
1579 clear();
1580}
1581
1582void RawPointerAxes::clear() {
1583 x.clear();
1584 y.clear();
1585 pressure.clear();
1586 touchMajor.clear();
1587 touchMinor.clear();
1588 toolMajor.clear();
1589 toolMinor.clear();
1590 orientation.clear();
1591 distance.clear();
1592 tiltX.clear();
1593 tiltY.clear();
1594 trackingId.clear();
1595 slot.clear();
1596}
1597
1598
1599// --- RawPointerData ---
1600
1601RawPointerData::RawPointerData() {
1602 clear();
1603}
1604
1605void RawPointerData::clear() {
1606 pointerCount = 0;
1607 clearIdBits();
1608}
1609
1610void RawPointerData::copyFrom(const RawPointerData& other) {
1611 pointerCount = other.pointerCount;
1612 hoveringIdBits = other.hoveringIdBits;
1613 touchingIdBits = other.touchingIdBits;
1614
1615 for (uint32_t i = 0; i < pointerCount; i++) {
1616 pointers[i] = other.pointers[i];
1617
1618 int id = pointers[i].id;
1619 idToIndex[id] = other.idToIndex[id];
1620 }
1621}
1622
1623void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1624 float x = 0, y = 0;
1625 uint32_t count = touchingIdBits.count();
1626 if (count) {
1627 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1628 uint32_t id = idBits.clearFirstMarkedBit();
1629 const Pointer& pointer = pointerForId(id);
1630 x += pointer.x;
1631 y += pointer.y;
1632 }
1633 x /= count;
1634 y /= count;
1635 }
1636 *outX = x;
1637 *outY = y;
1638}
1639
1640
1641// --- CookedPointerData ---
1642
1643CookedPointerData::CookedPointerData() {
1644 clear();
1645}
1646
1647void CookedPointerData::clear() {
1648 pointerCount = 0;
1649 hoveringIdBits.clear();
1650 touchingIdBits.clear();
1651}
1652
1653void CookedPointerData::copyFrom(const CookedPointerData& other) {
1654 pointerCount = other.pointerCount;
1655 hoveringIdBits = other.hoveringIdBits;
1656 touchingIdBits = other.touchingIdBits;
1657
1658 for (uint32_t i = 0; i < pointerCount; i++) {
1659 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1660 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1661
1662 int id = pointerProperties[i].id;
1663 idToIndex[id] = other.idToIndex[id];
1664 }
1665}
1666
1667
1668// --- SingleTouchMotionAccumulator ---
1669
1670SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1671 clearAbsoluteAxes();
1672}
1673
1674void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1675 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1676 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1677 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1678 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1679 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1680 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1681 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1682}
1683
1684void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1685 mAbsX = 0;
1686 mAbsY = 0;
1687 mAbsPressure = 0;
1688 mAbsToolWidth = 0;
1689 mAbsDistance = 0;
1690 mAbsTiltX = 0;
1691 mAbsTiltY = 0;
1692}
1693
1694void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1695 if (rawEvent->type == EV_ABS) {
1696 switch (rawEvent->code) {
1697 case ABS_X:
1698 mAbsX = rawEvent->value;
1699 break;
1700 case ABS_Y:
1701 mAbsY = rawEvent->value;
1702 break;
1703 case ABS_PRESSURE:
1704 mAbsPressure = rawEvent->value;
1705 break;
1706 case ABS_TOOL_WIDTH:
1707 mAbsToolWidth = rawEvent->value;
1708 break;
1709 case ABS_DISTANCE:
1710 mAbsDistance = rawEvent->value;
1711 break;
1712 case ABS_TILT_X:
1713 mAbsTiltX = rawEvent->value;
1714 break;
1715 case ABS_TILT_Y:
1716 mAbsTiltY = rawEvent->value;
1717 break;
1718 }
1719 }
1720}
1721
1722
1723// --- MultiTouchMotionAccumulator ---
1724
1725MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001726 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001727 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001728}
1729
1730MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1731 delete[] mSlots;
1732}
1733
1734void MultiTouchMotionAccumulator::configure(InputDevice* device,
1735 size_t slotCount, bool usingSlotsProtocol) {
1736 mSlotCount = slotCount;
1737 mUsingSlotsProtocol = usingSlotsProtocol;
1738 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1739
1740 delete[] mSlots;
1741 mSlots = new Slot[slotCount];
1742}
1743
1744void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1745 // Unfortunately there is no way to read the initial contents of the slots.
1746 // So when we reset the accumulator, we must assume they are all zeroes.
1747 if (mUsingSlotsProtocol) {
1748 // Query the driver for the current slot index and use it as the initial slot
1749 // before we start reading events from the device. It is possible that the
1750 // current slot index will not be the same as it was when the first event was
1751 // written into the evdev buffer, which means the input mapper could start
1752 // out of sync with the initial state of the events in the evdev buffer.
1753 // In the extremely unlikely case that this happens, the data from
1754 // two slots will be confused until the next ABS_MT_SLOT event is received.
1755 // This can cause the touch point to "jump", but at least there will be
1756 // no stuck touches.
1757 int32_t initialSlot;
1758 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1759 ABS_MT_SLOT, &initialSlot);
1760 if (status) {
1761 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1762 initialSlot = -1;
1763 }
1764 clearSlots(initialSlot);
1765 } else {
1766 clearSlots(-1);
1767 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001768 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001769}
1770
1771void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1772 if (mSlots) {
1773 for (size_t i = 0; i < mSlotCount; i++) {
1774 mSlots[i].clear();
1775 }
1776 }
1777 mCurrentSlot = initialSlot;
1778}
1779
1780void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1781 if (rawEvent->type == EV_ABS) {
1782 bool newSlot = false;
1783 if (mUsingSlotsProtocol) {
1784 if (rawEvent->code == ABS_MT_SLOT) {
1785 mCurrentSlot = rawEvent->value;
1786 newSlot = true;
1787 }
1788 } else if (mCurrentSlot < 0) {
1789 mCurrentSlot = 0;
1790 }
1791
1792 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1793#if DEBUG_POINTERS
1794 if (newSlot) {
1795 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001796 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001797 mCurrentSlot, mSlotCount - 1);
1798 }
1799#endif
1800 } else {
1801 Slot* slot = &mSlots[mCurrentSlot];
1802
1803 switch (rawEvent->code) {
1804 case ABS_MT_POSITION_X:
1805 slot->mInUse = true;
1806 slot->mAbsMTPositionX = rawEvent->value;
1807 break;
1808 case ABS_MT_POSITION_Y:
1809 slot->mInUse = true;
1810 slot->mAbsMTPositionY = rawEvent->value;
1811 break;
1812 case ABS_MT_TOUCH_MAJOR:
1813 slot->mInUse = true;
1814 slot->mAbsMTTouchMajor = rawEvent->value;
1815 break;
1816 case ABS_MT_TOUCH_MINOR:
1817 slot->mInUse = true;
1818 slot->mAbsMTTouchMinor = rawEvent->value;
1819 slot->mHaveAbsMTTouchMinor = true;
1820 break;
1821 case ABS_MT_WIDTH_MAJOR:
1822 slot->mInUse = true;
1823 slot->mAbsMTWidthMajor = rawEvent->value;
1824 break;
1825 case ABS_MT_WIDTH_MINOR:
1826 slot->mInUse = true;
1827 slot->mAbsMTWidthMinor = rawEvent->value;
1828 slot->mHaveAbsMTWidthMinor = true;
1829 break;
1830 case ABS_MT_ORIENTATION:
1831 slot->mInUse = true;
1832 slot->mAbsMTOrientation = rawEvent->value;
1833 break;
1834 case ABS_MT_TRACKING_ID:
1835 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1836 // The slot is no longer in use but it retains its previous contents,
1837 // which may be reused for subsequent touches.
1838 slot->mInUse = false;
1839 } else {
1840 slot->mInUse = true;
1841 slot->mAbsMTTrackingId = rawEvent->value;
1842 }
1843 break;
1844 case ABS_MT_PRESSURE:
1845 slot->mInUse = true;
1846 slot->mAbsMTPressure = rawEvent->value;
1847 break;
1848 case ABS_MT_DISTANCE:
1849 slot->mInUse = true;
1850 slot->mAbsMTDistance = rawEvent->value;
1851 break;
1852 case ABS_MT_TOOL_TYPE:
1853 slot->mInUse = true;
1854 slot->mAbsMTToolType = rawEvent->value;
1855 slot->mHaveAbsMTToolType = true;
1856 break;
1857 }
1858 }
1859 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1860 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1861 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001862 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1863 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001864 }
1865}
1866
1867void MultiTouchMotionAccumulator::finishSync() {
1868 if (!mUsingSlotsProtocol) {
1869 clearSlots(-1);
1870 }
1871}
1872
1873bool MultiTouchMotionAccumulator::hasStylus() const {
1874 return mHaveStylus;
1875}
1876
1877
1878// --- MultiTouchMotionAccumulator::Slot ---
1879
1880MultiTouchMotionAccumulator::Slot::Slot() {
1881 clear();
1882}
1883
1884void MultiTouchMotionAccumulator::Slot::clear() {
1885 mInUse = false;
1886 mHaveAbsMTTouchMinor = false;
1887 mHaveAbsMTWidthMinor = false;
1888 mHaveAbsMTToolType = false;
1889 mAbsMTPositionX = 0;
1890 mAbsMTPositionY = 0;
1891 mAbsMTTouchMajor = 0;
1892 mAbsMTTouchMinor = 0;
1893 mAbsMTWidthMajor = 0;
1894 mAbsMTWidthMinor = 0;
1895 mAbsMTOrientation = 0;
1896 mAbsMTTrackingId = -1;
1897 mAbsMTPressure = 0;
1898 mAbsMTDistance = 0;
1899 mAbsMTToolType = 0;
1900}
1901
1902int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1903 if (mHaveAbsMTToolType) {
1904 switch (mAbsMTToolType) {
1905 case MT_TOOL_FINGER:
1906 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1907 case MT_TOOL_PEN:
1908 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1909 }
1910 }
1911 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1912}
1913
1914
1915// --- InputMapper ---
1916
1917InputMapper::InputMapper(InputDevice* device) :
1918 mDevice(device), mContext(device->getContext()) {
1919}
1920
1921InputMapper::~InputMapper() {
1922}
1923
1924void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1925 info->addSource(getSources());
1926}
1927
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001928void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001929}
1930
1931void InputMapper::configure(nsecs_t when,
1932 const InputReaderConfiguration* config, uint32_t changes) {
1933}
1934
1935void InputMapper::reset(nsecs_t when) {
1936}
1937
1938void InputMapper::timeoutExpired(nsecs_t when) {
1939}
1940
1941int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1942 return AKEY_STATE_UNKNOWN;
1943}
1944
1945int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1946 return AKEY_STATE_UNKNOWN;
1947}
1948
1949int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1950 return AKEY_STATE_UNKNOWN;
1951}
1952
1953bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1954 const int32_t* keyCodes, uint8_t* outFlags) {
1955 return false;
1956}
1957
1958void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1959 int32_t token) {
1960}
1961
1962void InputMapper::cancelVibrate(int32_t token) {
1963}
1964
Jeff Brownc9aa6282015-02-11 19:03:28 -08001965void InputMapper::cancelTouch(nsecs_t when) {
1966}
1967
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968int32_t InputMapper::getMetaState() {
1969 return 0;
1970}
1971
Andrii Kulian763a3a42016-03-08 10:46:16 -08001972void InputMapper::updateMetaState(int32_t keyCode) {
1973}
1974
Michael Wright842500e2015-03-13 17:32:02 -07001975void InputMapper::updateExternalStylusState(const StylusState& state) {
1976
1977}
1978
Michael Wrightd02c5b62014-02-10 15:10:22 -08001979void InputMapper::fadePointer() {
1980}
1981
1982status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1983 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1984}
1985
1986void InputMapper::bumpGeneration() {
1987 mDevice->bumpGeneration();
1988}
1989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001990void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 const RawAbsoluteAxisInfo& axis, const char* name) {
1992 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001993 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1995 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001996 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997 }
1998}
1999
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002000void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2001 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2002 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2003 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2004 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002005}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
2007// --- SwitchInputMapper ---
2008
2009SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002010 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011}
2012
2013SwitchInputMapper::~SwitchInputMapper() {
2014}
2015
2016uint32_t SwitchInputMapper::getSources() {
2017 return AINPUT_SOURCE_SWITCH;
2018}
2019
2020void SwitchInputMapper::process(const RawEvent* rawEvent) {
2021 switch (rawEvent->type) {
2022 case EV_SW:
2023 processSwitch(rawEvent->code, rawEvent->value);
2024 break;
2025
2026 case EV_SYN:
2027 if (rawEvent->code == SYN_REPORT) {
2028 sync(rawEvent->when);
2029 }
2030 }
2031}
2032
2033void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2034 if (switchCode >= 0 && switchCode < 32) {
2035 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002036 mSwitchValues |= 1 << switchCode;
2037 } else {
2038 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002039 }
2040 mUpdatedSwitchMask |= 1 << switchCode;
2041 }
2042}
2043
2044void SwitchInputMapper::sync(nsecs_t when) {
2045 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002046 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002047 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2048 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002049 getListener()->notifySwitch(&args);
2050
Michael Wrightd02c5b62014-02-10 15:10:22 -08002051 mUpdatedSwitchMask = 0;
2052 }
2053}
2054
2055int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2056 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2057}
2058
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002059void SwitchInputMapper::dump(std::string& dump) {
2060 dump += INDENT2 "Switch Input Mapper:\n";
2061 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002062}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063
2064// --- VibratorInputMapper ---
2065
2066VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2067 InputMapper(device), mVibrating(false) {
2068}
2069
2070VibratorInputMapper::~VibratorInputMapper() {
2071}
2072
2073uint32_t VibratorInputMapper::getSources() {
2074 return 0;
2075}
2076
2077void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2078 InputMapper::populateDeviceInfo(info);
2079
2080 info->setVibrator(true);
2081}
2082
2083void VibratorInputMapper::process(const RawEvent* rawEvent) {
2084 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2085}
2086
2087void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2088 int32_t token) {
2089#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002090 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 for (size_t i = 0; i < patternSize; i++) {
2092 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002093 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002094 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002095 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002097 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002098 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002099#endif
2100
2101 mVibrating = true;
2102 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2103 mPatternSize = patternSize;
2104 mRepeat = repeat;
2105 mToken = token;
2106 mIndex = -1;
2107
2108 nextStep();
2109}
2110
2111void VibratorInputMapper::cancelVibrate(int32_t token) {
2112#if DEBUG_VIBRATOR
2113 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2114#endif
2115
2116 if (mVibrating && mToken == token) {
2117 stopVibrating();
2118 }
2119}
2120
2121void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2122 if (mVibrating) {
2123 if (when >= mNextStepTime) {
2124 nextStep();
2125 } else {
2126 getContext()->requestTimeoutAtTime(mNextStepTime);
2127 }
2128 }
2129}
2130
2131void VibratorInputMapper::nextStep() {
2132 mIndex += 1;
2133 if (size_t(mIndex) >= mPatternSize) {
2134 if (mRepeat < 0) {
2135 // We are done.
2136 stopVibrating();
2137 return;
2138 }
2139 mIndex = mRepeat;
2140 }
2141
2142 bool vibratorOn = mIndex & 1;
2143 nsecs_t duration = mPattern[mIndex];
2144 if (vibratorOn) {
2145#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002146 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147#endif
2148 getEventHub()->vibrate(getDeviceId(), duration);
2149 } else {
2150#if DEBUG_VIBRATOR
2151 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2152#endif
2153 getEventHub()->cancelVibrate(getDeviceId());
2154 }
2155 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2156 mNextStepTime = now + duration;
2157 getContext()->requestTimeoutAtTime(mNextStepTime);
2158#if DEBUG_VIBRATOR
2159 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2160#endif
2161}
2162
2163void VibratorInputMapper::stopVibrating() {
2164 mVibrating = false;
2165#if DEBUG_VIBRATOR
2166 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2167#endif
2168 getEventHub()->cancelVibrate(getDeviceId());
2169}
2170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002171void VibratorInputMapper::dump(std::string& dump) {
2172 dump += INDENT2 "Vibrator Input Mapper:\n";
2173 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002174}
2175
2176
2177// --- KeyboardInputMapper ---
2178
2179KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2180 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002181 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002182}
2183
2184KeyboardInputMapper::~KeyboardInputMapper() {
2185}
2186
2187uint32_t KeyboardInputMapper::getSources() {
2188 return mSource;
2189}
2190
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002191int32_t KeyboardInputMapper::getOrientation() {
2192 if (mViewport) {
2193 return mViewport->orientation;
2194 }
2195 return DISPLAY_ORIENTATION_0;
2196}
2197
2198int32_t KeyboardInputMapper::getDisplayId() {
2199 if (mViewport) {
2200 return mViewport->displayId;
2201 }
2202 return ADISPLAY_ID_NONE;
2203}
2204
Michael Wrightd02c5b62014-02-10 15:10:22 -08002205void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2206 InputMapper::populateDeviceInfo(info);
2207
2208 info->setKeyboardType(mKeyboardType);
2209 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2210}
2211
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002212void KeyboardInputMapper::dump(std::string& dump) {
2213 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002214 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002215 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002216 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002217 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2218 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2219 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002220}
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222void KeyboardInputMapper::configure(nsecs_t when,
2223 const InputReaderConfiguration* config, uint32_t changes) {
2224 InputMapper::configure(when, config, changes);
2225
2226 if (!changes) { // first time only
2227 // Configure basic parameters.
2228 configureParameters();
2229 }
2230
2231 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002232 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002233 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
2235 }
2236}
2237
Ivan Podogovb9afef32017-02-13 15:34:32 +00002238static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2239 int32_t mapped = 0;
2240 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2241 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2242 if (stemKeyRotationMap[i][0] == keyCode) {
2243 stemKeyRotationMap[i][1] = mapped;
2244 return;
2245 }
2246 }
2247 }
2248}
2249
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250void KeyboardInputMapper::configureParameters() {
2251 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002252 const PropertyMap& config = getDevice()->getConfiguration();
2253 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 mParameters.orientationAware);
2255
Michael Wrightd02c5b62014-02-10 15:10:22 -08002256 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002257 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2258 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2259 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2260 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002261 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002262
2263 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002264 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002265 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266}
2267
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002268void KeyboardInputMapper::dumpParameters(std::string& dump) {
2269 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002270 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002272 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002273 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002274}
2275
2276void KeyboardInputMapper::reset(nsecs_t when) {
2277 mMetaState = AMETA_NONE;
2278 mDownTime = 0;
2279 mKeyDowns.clear();
2280 mCurrentHidUsage = 0;
2281
2282 resetLedState();
2283
2284 InputMapper::reset(when);
2285}
2286
2287void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2288 switch (rawEvent->type) {
2289 case EV_KEY: {
2290 int32_t scanCode = rawEvent->code;
2291 int32_t usageCode = mCurrentHidUsage;
2292 mCurrentHidUsage = 0;
2293
2294 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002295 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002296 }
2297 break;
2298 }
2299 case EV_MSC: {
2300 if (rawEvent->code == MSC_SCAN) {
2301 mCurrentHidUsage = rawEvent->value;
2302 }
2303 break;
2304 }
2305 case EV_SYN: {
2306 if (rawEvent->code == SYN_REPORT) {
2307 mCurrentHidUsage = 0;
2308 }
2309 }
2310 }
2311}
2312
2313bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2314 return scanCode < BTN_MOUSE
2315 || scanCode >= KEY_OK
2316 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2317 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2318}
2319
Michael Wright58ba9882017-07-26 16:19:11 +01002320bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2321 switch (keyCode) {
2322 case AKEYCODE_MEDIA_PLAY:
2323 case AKEYCODE_MEDIA_PAUSE:
2324 case AKEYCODE_MEDIA_PLAY_PAUSE:
2325 case AKEYCODE_MUTE:
2326 case AKEYCODE_HEADSETHOOK:
2327 case AKEYCODE_MEDIA_STOP:
2328 case AKEYCODE_MEDIA_NEXT:
2329 case AKEYCODE_MEDIA_PREVIOUS:
2330 case AKEYCODE_MEDIA_REWIND:
2331 case AKEYCODE_MEDIA_RECORD:
2332 case AKEYCODE_MEDIA_FAST_FORWARD:
2333 case AKEYCODE_MEDIA_SKIP_FORWARD:
2334 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2335 case AKEYCODE_MEDIA_STEP_FORWARD:
2336 case AKEYCODE_MEDIA_STEP_BACKWARD:
2337 case AKEYCODE_MEDIA_AUDIO_TRACK:
2338 case AKEYCODE_VOLUME_UP:
2339 case AKEYCODE_VOLUME_DOWN:
2340 case AKEYCODE_VOLUME_MUTE:
2341 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2342 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2343 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2344 return true;
2345 }
2346 return false;
2347}
2348
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002349void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2350 int32_t usageCode) {
2351 int32_t keyCode;
2352 int32_t keyMetaState;
2353 uint32_t policyFlags;
2354
2355 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2356 &keyCode, &keyMetaState, &policyFlags)) {
2357 keyCode = AKEYCODE_UNKNOWN;
2358 keyMetaState = mMetaState;
2359 policyFlags = 0;
2360 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002361
2362 if (down) {
2363 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002364 if (mParameters.orientationAware) {
2365 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002366 }
2367
2368 // Add key down.
2369 ssize_t keyDownIndex = findKeyDown(scanCode);
2370 if (keyDownIndex >= 0) {
2371 // key repeat, be sure to use same keycode as before in case of rotation
2372 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2373 } else {
2374 // key down
2375 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2376 && mContext->shouldDropVirtualKey(when,
2377 getDevice(), keyCode, scanCode)) {
2378 return;
2379 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002380 if (policyFlags & POLICY_FLAG_GESTURE) {
2381 mDevice->cancelTouch(when);
2382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002383
2384 mKeyDowns.push();
2385 KeyDown& keyDown = mKeyDowns.editTop();
2386 keyDown.keyCode = keyCode;
2387 keyDown.scanCode = scanCode;
2388 }
2389
2390 mDownTime = when;
2391 } else {
2392 // Remove key down.
2393 ssize_t keyDownIndex = findKeyDown(scanCode);
2394 if (keyDownIndex >= 0) {
2395 // key up, be sure to use same keycode as before in case of rotation
2396 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2397 mKeyDowns.removeAt(size_t(keyDownIndex));
2398 } else {
2399 // key was not actually down
2400 ALOGI("Dropping key up from device %s because the key was not down. "
2401 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002402 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002403 return;
2404 }
2405 }
2406
Andrii Kulian763a3a42016-03-08 10:46:16 -08002407 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002408 // If global meta state changed send it along with the key.
2409 // If it has not changed then we'll use what keymap gave us,
2410 // since key replacement logic might temporarily reset a few
2411 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002412 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002413 }
2414
2415 nsecs_t downTime = mDownTime;
2416
2417 // Key down on external an keyboard should wake the device.
2418 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2419 // For internal keyboards, the key layout file should specify the policy flags for
2420 // each wake key individually.
2421 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002422 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002423 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 }
2425
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002426 if (mParameters.handlesKeyRepeat) {
2427 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2428 }
2429
Prabir Pradhan42611e02018-11-27 14:04:02 -08002430 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2431 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002432 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002433 getListener()->notifyKey(&args);
2434}
2435
2436ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2437 size_t n = mKeyDowns.size();
2438 for (size_t i = 0; i < n; i++) {
2439 if (mKeyDowns[i].scanCode == scanCode) {
2440 return i;
2441 }
2442 }
2443 return -1;
2444}
2445
2446int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2447 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2448}
2449
2450int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2451 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2452}
2453
2454bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2455 const int32_t* keyCodes, uint8_t* outFlags) {
2456 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2457}
2458
2459int32_t KeyboardInputMapper::getMetaState() {
2460 return mMetaState;
2461}
2462
Andrii Kulian763a3a42016-03-08 10:46:16 -08002463void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2464 updateMetaStateIfNeeded(keyCode, false);
2465}
2466
2467bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2468 int32_t oldMetaState = mMetaState;
2469 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2470 bool metaStateChanged = oldMetaState != newMetaState;
2471 if (metaStateChanged) {
2472 mMetaState = newMetaState;
2473 updateLedState(false);
2474
2475 getContext()->updateGlobalMetaState();
2476 }
2477
2478 return metaStateChanged;
2479}
2480
Michael Wrightd02c5b62014-02-10 15:10:22 -08002481void KeyboardInputMapper::resetLedState() {
2482 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2483 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2484 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2485
2486 updateLedState(true);
2487}
2488
2489void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2490 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2491 ledState.on = false;
2492}
2493
2494void KeyboardInputMapper::updateLedState(bool reset) {
2495 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2496 AMETA_CAPS_LOCK_ON, reset);
2497 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2498 AMETA_NUM_LOCK_ON, reset);
2499 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2500 AMETA_SCROLL_LOCK_ON, reset);
2501}
2502
2503void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2504 int32_t led, int32_t modifier, bool reset) {
2505 if (ledState.avail) {
2506 bool desiredState = (mMetaState & modifier) != 0;
2507 if (reset || ledState.on != desiredState) {
2508 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2509 ledState.on = desiredState;
2510 }
2511 }
2512}
2513
2514
2515// --- CursorInputMapper ---
2516
2517CursorInputMapper::CursorInputMapper(InputDevice* device) :
2518 InputMapper(device) {
2519}
2520
2521CursorInputMapper::~CursorInputMapper() {
2522}
2523
2524uint32_t CursorInputMapper::getSources() {
2525 return mSource;
2526}
2527
2528void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2529 InputMapper::populateDeviceInfo(info);
2530
2531 if (mParameters.mode == Parameters::MODE_POINTER) {
2532 float minX, minY, maxX, maxY;
2533 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2534 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2535 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2536 }
2537 } else {
2538 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2539 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2540 }
2541 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2542
2543 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2544 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2545 }
2546 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2547 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2548 }
2549}
2550
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002551void CursorInputMapper::dump(std::string& dump) {
2552 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002553 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002554 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2555 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2556 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2557 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2558 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002559 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002560 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002562 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2563 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2564 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2565 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2566 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2567 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002568}
2569
2570void CursorInputMapper::configure(nsecs_t when,
2571 const InputReaderConfiguration* config, uint32_t changes) {
2572 InputMapper::configure(when, config, changes);
2573
2574 if (!changes) { // first time only
2575 mCursorScrollAccumulator.configure(getDevice());
2576
2577 // Configure basic parameters.
2578 configureParameters();
2579
2580 // Configure device mode.
2581 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002582 case Parameters::MODE_POINTER_RELATIVE:
2583 // Should not happen during first time configuration.
2584 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2585 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002586 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002587 case Parameters::MODE_POINTER:
2588 mSource = AINPUT_SOURCE_MOUSE;
2589 mXPrecision = 1.0f;
2590 mYPrecision = 1.0f;
2591 mXScale = 1.0f;
2592 mYScale = 1.0f;
2593 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2594 break;
2595 case Parameters::MODE_NAVIGATION:
2596 mSource = AINPUT_SOURCE_TRACKBALL;
2597 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2598 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2599 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2600 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2601 break;
2602 }
2603
2604 mVWheelScale = 1.0f;
2605 mHWheelScale = 1.0f;
2606 }
2607
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002608 if ((!changes && config->pointerCapture)
2609 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2610 if (config->pointerCapture) {
2611 if (mParameters.mode == Parameters::MODE_POINTER) {
2612 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2613 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2614 // Keep PointerController around in order to preserve the pointer position.
2615 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2616 } else {
2617 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2618 }
2619 } else {
2620 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2621 mParameters.mode = Parameters::MODE_POINTER;
2622 mSource = AINPUT_SOURCE_MOUSE;
2623 } else {
2624 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2625 }
2626 }
2627 bumpGeneration();
2628 if (changes) {
2629 getDevice()->notifyReset(when);
2630 }
2631 }
2632
Michael Wrightd02c5b62014-02-10 15:10:22 -08002633 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2634 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2635 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2636 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2637 }
2638
2639 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002640 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002641 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002642 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002643 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002644 if (internalViewport) {
2645 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002648
2649 // Update the PointerController if viewports changed.
2650 if (mParameters.hasAssociatedDisplay) {
2651 getPolicy()->obtainPointerController(getDeviceId());
2652 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002653 bumpGeneration();
2654 }
2655}
2656
2657void CursorInputMapper::configureParameters() {
2658 mParameters.mode = Parameters::MODE_POINTER;
2659 String8 cursorModeString;
2660 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2661 if (cursorModeString == "navigation") {
2662 mParameters.mode = Parameters::MODE_NAVIGATION;
2663 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2664 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2665 }
2666 }
2667
2668 mParameters.orientationAware = false;
2669 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2670 mParameters.orientationAware);
2671
2672 mParameters.hasAssociatedDisplay = false;
2673 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2674 mParameters.hasAssociatedDisplay = true;
2675 }
2676}
2677
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002678void CursorInputMapper::dumpParameters(std::string& dump) {
2679 dump += INDENT3 "Parameters:\n";
2680 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 toString(mParameters.hasAssociatedDisplay));
2682
2683 switch (mParameters.mode) {
2684 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002685 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002687 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002688 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002689 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002690 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002691 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002692 break;
2693 default:
2694 ALOG_ASSERT(false);
2695 }
2696
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002697 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002698 toString(mParameters.orientationAware));
2699}
2700
2701void CursorInputMapper::reset(nsecs_t when) {
2702 mButtonState = 0;
2703 mDownTime = 0;
2704
2705 mPointerVelocityControl.reset();
2706 mWheelXVelocityControl.reset();
2707 mWheelYVelocityControl.reset();
2708
2709 mCursorButtonAccumulator.reset(getDevice());
2710 mCursorMotionAccumulator.reset(getDevice());
2711 mCursorScrollAccumulator.reset(getDevice());
2712
2713 InputMapper::reset(when);
2714}
2715
2716void CursorInputMapper::process(const RawEvent* rawEvent) {
2717 mCursorButtonAccumulator.process(rawEvent);
2718 mCursorMotionAccumulator.process(rawEvent);
2719 mCursorScrollAccumulator.process(rawEvent);
2720
2721 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2722 sync(rawEvent->when);
2723 }
2724}
2725
2726void CursorInputMapper::sync(nsecs_t when) {
2727 int32_t lastButtonState = mButtonState;
2728 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2729 mButtonState = currentButtonState;
2730
2731 bool wasDown = isPointerDown(lastButtonState);
2732 bool down = isPointerDown(currentButtonState);
2733 bool downChanged;
2734 if (!wasDown && down) {
2735 mDownTime = when;
2736 downChanged = true;
2737 } else if (wasDown && !down) {
2738 downChanged = true;
2739 } else {
2740 downChanged = false;
2741 }
2742 nsecs_t downTime = mDownTime;
2743 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002744 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2745 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002746
2747 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2748 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2749 bool moved = deltaX != 0 || deltaY != 0;
2750
2751 // Rotate delta according to orientation if needed.
2752 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2753 && (deltaX != 0.0f || deltaY != 0.0f)) {
2754 rotateDelta(mOrientation, &deltaX, &deltaY);
2755 }
2756
2757 // Move the pointer.
2758 PointerProperties pointerProperties;
2759 pointerProperties.clear();
2760 pointerProperties.id = 0;
2761 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2762
2763 PointerCoords pointerCoords;
2764 pointerCoords.clear();
2765
2766 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2767 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2768 bool scrolled = vscroll != 0 || hscroll != 0;
2769
Yi Kong9b14ac62018-07-17 13:48:38 -07002770 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2771 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002772
2773 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2774
2775 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002776 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 if (moved || scrolled || buttonsChanged) {
2778 mPointerController->setPresentation(
2779 PointerControllerInterface::PRESENTATION_POINTER);
2780
2781 if (moved) {
2782 mPointerController->move(deltaX, deltaY);
2783 }
2784
2785 if (buttonsChanged) {
2786 mPointerController->setButtonState(currentButtonState);
2787 }
2788
2789 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2790 }
2791
2792 float x, y;
2793 mPointerController->getPosition(&x, &y);
2794 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2795 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002796 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2797 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002798 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002799 } else {
2800 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2801 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2802 displayId = ADISPLAY_ID_NONE;
2803 }
2804
2805 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2806
2807 // Moving an external trackball or mouse should wake the device.
2808 // We don't do this for internal cursor devices to prevent them from waking up
2809 // the device in your pocket.
2810 // TODO: Use the input device configuration to control this behavior more finely.
2811 uint32_t policyFlags = 0;
2812 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002813 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 }
2815
2816 // Synthesize key down from buttons if needed.
2817 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002818 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819
2820 // Send motion event.
2821 if (downChanged || moved || scrolled || buttonsChanged) {
2822 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002823 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 int32_t motionEventAction;
2825 if (downChanged) {
2826 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002827 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002828 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2829 } else {
2830 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2831 }
2832
Michael Wright7b159c92015-05-14 14:48:03 +01002833 if (buttonsReleased) {
2834 BitSet32 released(buttonsReleased);
2835 while (!released.isEmpty()) {
2836 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2837 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002838 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2839 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002840 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002841 metaState, buttonState,
2842 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002843 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002844 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002845 getListener()->notifyMotion(&releaseArgs);
2846 }
2847 }
2848
Prabir Pradhan42611e02018-11-27 14:04:02 -08002849 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2850 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002851 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002852 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002853 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002854 getListener()->notifyMotion(&args);
2855
Michael Wright7b159c92015-05-14 14:48:03 +01002856 if (buttonsPressed) {
2857 BitSet32 pressed(buttonsPressed);
2858 while (!pressed.isEmpty()) {
2859 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2860 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002861 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2862 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002863 actionButton, 0, metaState, buttonState,
2864 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002865 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002866 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002867 getListener()->notifyMotion(&pressArgs);
2868 }
2869 }
2870
2871 ALOG_ASSERT(buttonState == currentButtonState);
2872
Michael Wrightd02c5b62014-02-10 15:10:22 -08002873 // Send hover move after UP to tell the application that the mouse is hovering now.
2874 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002875 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002876 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2877 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002878 metaState, currentButtonState,
2879 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002880 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002881 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002882 getListener()->notifyMotion(&hoverArgs);
2883 }
2884
2885 // Send scroll events.
2886 if (scrolled) {
2887 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2888 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2889
Prabir Pradhan42611e02018-11-27 14:04:02 -08002890 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2891 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002892 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002893 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002894 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002895 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002896 getListener()->notifyMotion(&scrollArgs);
2897 }
2898 }
2899
2900 // Synthesize key up from buttons if needed.
2901 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002902 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002903
2904 mCursorMotionAccumulator.finishSync();
2905 mCursorScrollAccumulator.finishSync();
2906}
2907
2908int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2909 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2910 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2911 } else {
2912 return AKEY_STATE_UNKNOWN;
2913 }
2914}
2915
2916void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002917 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002918 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2919 }
2920}
2921
Prashant Malani1941ff52015-08-11 18:29:28 -07002922// --- RotaryEncoderInputMapper ---
2923
2924RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002925 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002926 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2927}
2928
2929RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2930}
2931
2932uint32_t RotaryEncoderInputMapper::getSources() {
2933 return mSource;
2934}
2935
2936void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2937 InputMapper::populateDeviceInfo(info);
2938
2939 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002940 float res = 0.0f;
2941 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2942 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2943 }
2944 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2945 mScalingFactor)) {
2946 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2947 "default to 1.0!\n");
2948 mScalingFactor = 1.0f;
2949 }
2950 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2951 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002952 }
2953}
2954
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002955void RotaryEncoderInputMapper::dump(std::string& dump) {
2956 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2957 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002958 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2959}
2960
2961void RotaryEncoderInputMapper::configure(nsecs_t when,
2962 const InputReaderConfiguration* config, uint32_t changes) {
2963 InputMapper::configure(when, config, changes);
2964 if (!changes) {
2965 mRotaryEncoderScrollAccumulator.configure(getDevice());
2966 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002967 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002968 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002969 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002970 if (internalViewport) {
2971 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002972 } else {
2973 mOrientation = DISPLAY_ORIENTATION_0;
2974 }
2975 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002976}
2977
2978void RotaryEncoderInputMapper::reset(nsecs_t when) {
2979 mRotaryEncoderScrollAccumulator.reset(getDevice());
2980
2981 InputMapper::reset(when);
2982}
2983
2984void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2985 mRotaryEncoderScrollAccumulator.process(rawEvent);
2986
2987 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2988 sync(rawEvent->when);
2989 }
2990}
2991
2992void RotaryEncoderInputMapper::sync(nsecs_t when) {
2993 PointerCoords pointerCoords;
2994 pointerCoords.clear();
2995
2996 PointerProperties pointerProperties;
2997 pointerProperties.clear();
2998 pointerProperties.id = 0;
2999 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3000
3001 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3002 bool scrolled = scroll != 0;
3003
3004 // This is not a pointer, so it's not associated with a display.
3005 int32_t displayId = ADISPLAY_ID_NONE;
3006
3007 // Moving the rotary encoder should wake the device (if specified).
3008 uint32_t policyFlags = 0;
3009 if (scrolled && getDevice()->isExternal()) {
3010 policyFlags |= POLICY_FLAG_WAKE;
3011 }
3012
Ivan Podogovad437252016-09-29 16:29:55 +01003013 if (mOrientation == DISPLAY_ORIENTATION_180) {
3014 scroll = -scroll;
3015 }
3016
Prashant Malani1941ff52015-08-11 18:29:28 -07003017 // Send motion event.
3018 if (scrolled) {
3019 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003020 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003021
Prabir Pradhan42611e02018-11-27 14:04:02 -08003022 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3023 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08003024 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0,
3025 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003026 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003027 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003028 getListener()->notifyMotion(&scrollArgs);
3029 }
3030
3031 mRotaryEncoderScrollAccumulator.finishSync();
3032}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003033
3034// --- TouchInputMapper ---
3035
3036TouchInputMapper::TouchInputMapper(InputDevice* device) :
3037 InputMapper(device),
3038 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3039 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003040 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003041 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3042}
3043
3044TouchInputMapper::~TouchInputMapper() {
3045}
3046
3047uint32_t TouchInputMapper::getSources() {
3048 return mSource;
3049}
3050
3051void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3052 InputMapper::populateDeviceInfo(info);
3053
3054 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3055 info->addMotionRange(mOrientedRanges.x);
3056 info->addMotionRange(mOrientedRanges.y);
3057 info->addMotionRange(mOrientedRanges.pressure);
3058
3059 if (mOrientedRanges.haveSize) {
3060 info->addMotionRange(mOrientedRanges.size);
3061 }
3062
3063 if (mOrientedRanges.haveTouchSize) {
3064 info->addMotionRange(mOrientedRanges.touchMajor);
3065 info->addMotionRange(mOrientedRanges.touchMinor);
3066 }
3067
3068 if (mOrientedRanges.haveToolSize) {
3069 info->addMotionRange(mOrientedRanges.toolMajor);
3070 info->addMotionRange(mOrientedRanges.toolMinor);
3071 }
3072
3073 if (mOrientedRanges.haveOrientation) {
3074 info->addMotionRange(mOrientedRanges.orientation);
3075 }
3076
3077 if (mOrientedRanges.haveDistance) {
3078 info->addMotionRange(mOrientedRanges.distance);
3079 }
3080
3081 if (mOrientedRanges.haveTilt) {
3082 info->addMotionRange(mOrientedRanges.tilt);
3083 }
3084
3085 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3086 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3087 0.0f);
3088 }
3089 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3090 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3091 0.0f);
3092 }
3093 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3094 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3095 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3096 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3097 x.fuzz, x.resolution);
3098 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3099 y.fuzz, y.resolution);
3100 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3101 x.fuzz, x.resolution);
3102 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3103 y.fuzz, y.resolution);
3104 }
3105 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3106 }
3107}
3108
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003109void TouchInputMapper::dump(std::string& dump) {
3110 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003111 dumpParameters(dump);
3112 dumpVirtualKeys(dump);
3113 dumpRawPointerAxes(dump);
3114 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003115 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003116 dumpSurface(dump);
3117
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003118 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3119 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3120 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3121 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3122 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3123 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3124 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3125 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3126 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3127 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3128 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3129 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3130 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3131 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3132 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3133 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3134 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003135
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003136 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3137 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003138 mLastRawState.rawPointerData.pointerCount);
3139 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3140 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003141 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3143 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3144 "toolType=%d, isHovering=%s\n", i,
3145 pointer.id, pointer.x, pointer.y, pointer.pressure,
3146 pointer.touchMajor, pointer.touchMinor,
3147 pointer.toolMajor, pointer.toolMinor,
3148 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3149 pointer.toolType, toString(pointer.isHovering));
3150 }
3151
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003152 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3153 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003154 mLastCookedState.cookedPointerData.pointerCount);
3155 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3156 const PointerProperties& pointerProperties =
3157 mLastCookedState.cookedPointerData.pointerProperties[i];
3158 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003159 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3161 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3162 "toolType=%d, isHovering=%s\n", i,
3163 pointerProperties.id,
3164 pointerCoords.getX(),
3165 pointerCoords.getY(),
3166 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3167 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3168 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3169 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3170 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3171 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3172 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3173 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3174 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003175 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 }
3177
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003178 dump += INDENT3 "Stylus Fusion:\n";
3179 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003180 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3182 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003183 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003184 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003185 dumpStylusState(dump, mExternalStylusState);
3186
Michael Wrightd02c5b62014-02-10 15:10:22 -08003187 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003188 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3189 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003191 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003193 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003195 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003196 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003197 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003198 mPointerGestureMaxSwipeWidth);
3199 }
3200}
3201
Santos Cordonfa5cf462017-04-05 10:37:00 -07003202const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3203 switch (deviceMode) {
3204 case DEVICE_MODE_DISABLED:
3205 return "disabled";
3206 case DEVICE_MODE_DIRECT:
3207 return "direct";
3208 case DEVICE_MODE_UNSCALED:
3209 return "unscaled";
3210 case DEVICE_MODE_NAVIGATION:
3211 return "navigation";
3212 case DEVICE_MODE_POINTER:
3213 return "pointer";
3214 }
3215 return "unknown";
3216}
3217
Michael Wrightd02c5b62014-02-10 15:10:22 -08003218void TouchInputMapper::configure(nsecs_t when,
3219 const InputReaderConfiguration* config, uint32_t changes) {
3220 InputMapper::configure(when, config, changes);
3221
3222 mConfig = *config;
3223
3224 if (!changes) { // first time only
3225 // Configure basic parameters.
3226 configureParameters();
3227
3228 // Configure common accumulators.
3229 mCursorScrollAccumulator.configure(getDevice());
3230 mTouchButtonAccumulator.configure(getDevice());
3231
3232 // Configure absolute axis information.
3233 configureRawPointerAxes();
3234
3235 // Prepare input device calibration.
3236 parseCalibration();
3237 resolveCalibration();
3238 }
3239
Michael Wright842500e2015-03-13 17:32:02 -07003240 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003241 // Update location calibration to reflect current settings
3242 updateAffineTransformation();
3243 }
3244
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3246 // Update pointer speed.
3247 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3248 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3249 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3250 }
3251
3252 bool resetNeeded = false;
3253 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3254 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003255 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3256 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003257 // Configure device sources, surface dimensions, orientation and
3258 // scaling factors.
3259 configureSurface(when, &resetNeeded);
3260 }
3261
3262 if (changes && resetNeeded) {
3263 // Send reset, unless this is the first time the device has been configured,
3264 // in which case the reader will call reset itself after all mappers are ready.
3265 getDevice()->notifyReset(when);
3266 }
3267}
3268
Michael Wright842500e2015-03-13 17:32:02 -07003269void TouchInputMapper::resolveExternalStylusPresence() {
3270 Vector<InputDeviceInfo> devices;
3271 mContext->getExternalStylusDevices(devices);
3272 mExternalStylusConnected = !devices.isEmpty();
3273
3274 if (!mExternalStylusConnected) {
3275 resetExternalStylus();
3276 }
3277}
3278
Michael Wrightd02c5b62014-02-10 15:10:22 -08003279void TouchInputMapper::configureParameters() {
3280 // Use the pointer presentation mode for devices that do not support distinct
3281 // multitouch. The spot-based presentation relies on being able to accurately
3282 // locate two or more fingers on the touch pad.
3283 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003284 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003285
3286 String8 gestureModeString;
3287 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3288 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003289 if (gestureModeString == "single-touch") {
3290 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3291 } else if (gestureModeString == "multi-touch") {
3292 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003293 } else if (gestureModeString != "default") {
3294 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3295 }
3296 }
3297
3298 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3299 // The device is a touch screen.
3300 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3301 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3302 // The device is a pointing device like a track pad.
3303 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3304 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3305 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3306 // The device is a cursor device with a touch pad attached.
3307 // By default don't use the touch pad to move the pointer.
3308 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3309 } else {
3310 // The device is a touch pad of unknown purpose.
3311 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3312 }
3313
3314 mParameters.hasButtonUnderPad=
3315 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3316
3317 String8 deviceTypeString;
3318 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3319 deviceTypeString)) {
3320 if (deviceTypeString == "touchScreen") {
3321 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3322 } else if (deviceTypeString == "touchPad") {
3323 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3324 } else if (deviceTypeString == "touchNavigation") {
3325 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3326 } else if (deviceTypeString == "pointer") {
3327 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3328 } else if (deviceTypeString != "default") {
3329 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3330 }
3331 }
3332
3333 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3334 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3335 mParameters.orientationAware);
3336
3337 mParameters.hasAssociatedDisplay = false;
3338 mParameters.associatedDisplayIsExternal = false;
3339 if (mParameters.orientationAware
3340 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3341 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3342 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003343 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3344 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003345 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003346 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003347 uniqueDisplayId);
3348 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003349 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003350 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003351 if (getDevice()->getAssociatedDisplayPort()) {
3352 mParameters.hasAssociatedDisplay = true;
3353 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003354
3355 // Initial downs on external touch devices should wake the device.
3356 // Normally we don't do this for internal touch screens to prevent them from waking
3357 // up in your pocket but you can enable it using the input device configuration.
3358 mParameters.wake = getDevice()->isExternal();
3359 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3360 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361}
3362
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003363void TouchInputMapper::dumpParameters(std::string& dump) {
3364 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365
3366 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003367 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003368 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003369 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003370 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003371 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003372 break;
3373 default:
3374 assert(false);
3375 }
3376
3377 switch (mParameters.deviceType) {
3378 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003379 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003380 break;
3381 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 break;
3384 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003385 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 break;
3387 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003388 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003389 break;
3390 default:
3391 ALOG_ASSERT(false);
3392 }
3393
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003394 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003395 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003397 toString(mParameters.associatedDisplayIsExternal),
3398 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003399 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003400 toString(mParameters.orientationAware));
3401}
3402
3403void TouchInputMapper::configureRawPointerAxes() {
3404 mRawPointerAxes.clear();
3405}
3406
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003407void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3408 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3410 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3411 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3412 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3413 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3414 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3415 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3416 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3417 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3418 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3419 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3420 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3421 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3422}
3423
Michael Wright842500e2015-03-13 17:32:02 -07003424bool TouchInputMapper::hasExternalStylus() const {
3425 return mExternalStylusConnected;
3426}
3427
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003428/**
3429 * Determine which DisplayViewport to use.
3430 * 1. If display port is specified, return the matching viewport. If matching viewport not
3431 * found, then return.
3432 * 2. If a device has associated display, get the matching viewport by either unique id or by
3433 * the display type (internal or external).
3434 * 3. Otherwise, use a non-display viewport.
3435 */
3436std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3437 if (mParameters.hasAssociatedDisplay) {
3438 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3439 if (displayPort) {
3440 // Find the viewport that contains the same port
3441 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3442 if (!v) {
3443 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3444 "but the corresponding viewport is not found.",
3445 getDeviceName().c_str(), *displayPort);
3446 }
3447 return v;
3448 }
3449
3450 if (!mParameters.uniqueDisplayId.empty()) {
3451 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3452 }
3453
3454 ViewportType viewportTypeToUse;
3455 if (mParameters.associatedDisplayIsExternal) {
3456 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3457 } else {
3458 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3459 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003460
3461 std::optional<DisplayViewport> viewport =
3462 mConfig.getDisplayViewportByType(viewportTypeToUse);
3463 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3464 ALOGW("Input device %s should be associated with external display, "
3465 "fallback to internal one for the external viewport is not found.",
3466 getDeviceName().c_str());
3467 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3468 }
3469
3470 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003471 }
3472
3473 DisplayViewport newViewport;
3474 // Raw width and height in the natural orientation.
3475 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3476 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3477 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3478 return std::make_optional(newViewport);
3479}
3480
Michael Wrightd02c5b62014-02-10 15:10:22 -08003481void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3482 int32_t oldDeviceMode = mDeviceMode;
3483
Michael Wright842500e2015-03-13 17:32:02 -07003484 resolveExternalStylusPresence();
3485
Michael Wrightd02c5b62014-02-10 15:10:22 -08003486 // Determine device mode.
3487 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3488 && mConfig.pointerGesturesEnabled) {
3489 mSource = AINPUT_SOURCE_MOUSE;
3490 mDeviceMode = DEVICE_MODE_POINTER;
3491 if (hasStylus()) {
3492 mSource |= AINPUT_SOURCE_STYLUS;
3493 }
3494 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3495 && mParameters.hasAssociatedDisplay) {
3496 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3497 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003498 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003499 mSource |= AINPUT_SOURCE_STYLUS;
3500 }
Michael Wright2f78b682015-06-12 15:25:08 +01003501 if (hasExternalStylus()) {
3502 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3503 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3505 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3506 mDeviceMode = DEVICE_MODE_NAVIGATION;
3507 } else {
3508 mSource = AINPUT_SOURCE_TOUCHPAD;
3509 mDeviceMode = DEVICE_MODE_UNSCALED;
3510 }
3511
3512 // Ensure we have valid X and Y axes.
3513 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003514 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003515 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 mDeviceMode = DEVICE_MODE_DISABLED;
3517 return;
3518 }
3519
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003520 // Get associated display dimensions.
3521 std::optional<DisplayViewport> newViewport = findViewport();
3522 if (!newViewport) {
3523 ALOGI("Touch device '%s' could not query the properties of its associated "
3524 "display. The device will be inoperable until the display size "
3525 "becomes available.",
3526 getDeviceName().c_str());
3527 mDeviceMode = DEVICE_MODE_DISABLED;
3528 return;
3529 }
3530
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003532 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3533 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003535 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003536 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003537 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003538
3539 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3540 // Convert rotated viewport to natural surface coordinates.
3541 int32_t naturalLogicalWidth, naturalLogicalHeight;
3542 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3543 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3544 int32_t naturalDeviceWidth, naturalDeviceHeight;
3545 switch (mViewport.orientation) {
3546 case DISPLAY_ORIENTATION_90:
3547 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3548 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3549 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3550 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3551 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3552 naturalPhysicalTop = mViewport.physicalLeft;
3553 naturalDeviceWidth = mViewport.deviceHeight;
3554 naturalDeviceHeight = mViewport.deviceWidth;
3555 break;
3556 case DISPLAY_ORIENTATION_180:
3557 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3558 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3559 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3560 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3561 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3562 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3563 naturalDeviceWidth = mViewport.deviceWidth;
3564 naturalDeviceHeight = mViewport.deviceHeight;
3565 break;
3566 case DISPLAY_ORIENTATION_270:
3567 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3568 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3569 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3570 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3571 naturalPhysicalLeft = mViewport.physicalTop;
3572 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3573 naturalDeviceWidth = mViewport.deviceHeight;
3574 naturalDeviceHeight = mViewport.deviceWidth;
3575 break;
3576 case DISPLAY_ORIENTATION_0:
3577 default:
3578 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3579 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3580 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3581 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3582 naturalPhysicalLeft = mViewport.physicalLeft;
3583 naturalPhysicalTop = mViewport.physicalTop;
3584 naturalDeviceWidth = mViewport.deviceWidth;
3585 naturalDeviceHeight = mViewport.deviceHeight;
3586 break;
3587 }
3588
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003589 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3590 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3591 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3592 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3593 }
3594
Michael Wright358bcc72018-08-21 04:01:07 +01003595 mPhysicalWidth = naturalPhysicalWidth;
3596 mPhysicalHeight = naturalPhysicalHeight;
3597 mPhysicalLeft = naturalPhysicalLeft;
3598 mPhysicalTop = naturalPhysicalTop;
3599
Michael Wrightd02c5b62014-02-10 15:10:22 -08003600 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3601 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3602 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3603 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3604
3605 mSurfaceOrientation = mParameters.orientationAware ?
3606 mViewport.orientation : DISPLAY_ORIENTATION_0;
3607 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003608 mPhysicalWidth = rawWidth;
3609 mPhysicalHeight = rawHeight;
3610 mPhysicalLeft = 0;
3611 mPhysicalTop = 0;
3612
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 mSurfaceWidth = rawWidth;
3614 mSurfaceHeight = rawHeight;
3615 mSurfaceLeft = 0;
3616 mSurfaceTop = 0;
3617 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3618 }
3619 }
3620
3621 // If moving between pointer modes, need to reset some state.
3622 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3623 if (deviceModeChanged) {
3624 mOrientedRanges.clear();
3625 }
3626
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003627 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003628 if (mDeviceMode == DEVICE_MODE_POINTER ||
3629 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003630 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003631 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3632 }
3633 } else {
3634 mPointerController.clear();
3635 }
3636
3637 if (viewportChanged || deviceModeChanged) {
3638 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3639 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003640 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003641 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3642
3643 // Configure X and Y factors.
3644 mXScale = float(mSurfaceWidth) / rawWidth;
3645 mYScale = float(mSurfaceHeight) / rawHeight;
3646 mXTranslate = -mSurfaceLeft;
3647 mYTranslate = -mSurfaceTop;
3648 mXPrecision = 1.0f / mXScale;
3649 mYPrecision = 1.0f / mYScale;
3650
3651 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3652 mOrientedRanges.x.source = mSource;
3653 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3654 mOrientedRanges.y.source = mSource;
3655
3656 configureVirtualKeys();
3657
3658 // Scale factor for terms that are not oriented in a particular axis.
3659 // If the pixels are square then xScale == yScale otherwise we fake it
3660 // by choosing an average.
3661 mGeometricScale = avg(mXScale, mYScale);
3662
3663 // Size of diagonal axis.
3664 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3665
3666 // Size factors.
3667 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3668 if (mRawPointerAxes.touchMajor.valid
3669 && mRawPointerAxes.touchMajor.maxValue != 0) {
3670 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3671 } else if (mRawPointerAxes.toolMajor.valid
3672 && mRawPointerAxes.toolMajor.maxValue != 0) {
3673 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3674 } else {
3675 mSizeScale = 0.0f;
3676 }
3677
3678 mOrientedRanges.haveTouchSize = true;
3679 mOrientedRanges.haveToolSize = true;
3680 mOrientedRanges.haveSize = true;
3681
3682 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3683 mOrientedRanges.touchMajor.source = mSource;
3684 mOrientedRanges.touchMajor.min = 0;
3685 mOrientedRanges.touchMajor.max = diagonalSize;
3686 mOrientedRanges.touchMajor.flat = 0;
3687 mOrientedRanges.touchMajor.fuzz = 0;
3688 mOrientedRanges.touchMajor.resolution = 0;
3689
3690 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3691 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3692
3693 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3694 mOrientedRanges.toolMajor.source = mSource;
3695 mOrientedRanges.toolMajor.min = 0;
3696 mOrientedRanges.toolMajor.max = diagonalSize;
3697 mOrientedRanges.toolMajor.flat = 0;
3698 mOrientedRanges.toolMajor.fuzz = 0;
3699 mOrientedRanges.toolMajor.resolution = 0;
3700
3701 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3702 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3703
3704 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3705 mOrientedRanges.size.source = mSource;
3706 mOrientedRanges.size.min = 0;
3707 mOrientedRanges.size.max = 1.0;
3708 mOrientedRanges.size.flat = 0;
3709 mOrientedRanges.size.fuzz = 0;
3710 mOrientedRanges.size.resolution = 0;
3711 } else {
3712 mSizeScale = 0.0f;
3713 }
3714
3715 // Pressure factors.
3716 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003717 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003718 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3719 || mCalibration.pressureCalibration
3720 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3721 if (mCalibration.havePressureScale) {
3722 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003723 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003724 } else if (mRawPointerAxes.pressure.valid
3725 && mRawPointerAxes.pressure.maxValue != 0) {
3726 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3727 }
3728 }
3729
3730 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3731 mOrientedRanges.pressure.source = mSource;
3732 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003733 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003734 mOrientedRanges.pressure.flat = 0;
3735 mOrientedRanges.pressure.fuzz = 0;
3736 mOrientedRanges.pressure.resolution = 0;
3737
3738 // Tilt
3739 mTiltXCenter = 0;
3740 mTiltXScale = 0;
3741 mTiltYCenter = 0;
3742 mTiltYScale = 0;
3743 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3744 if (mHaveTilt) {
3745 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3746 mRawPointerAxes.tiltX.maxValue);
3747 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3748 mRawPointerAxes.tiltY.maxValue);
3749 mTiltXScale = M_PI / 180;
3750 mTiltYScale = M_PI / 180;
3751
3752 mOrientedRanges.haveTilt = true;
3753
3754 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3755 mOrientedRanges.tilt.source = mSource;
3756 mOrientedRanges.tilt.min = 0;
3757 mOrientedRanges.tilt.max = M_PI_2;
3758 mOrientedRanges.tilt.flat = 0;
3759 mOrientedRanges.tilt.fuzz = 0;
3760 mOrientedRanges.tilt.resolution = 0;
3761 }
3762
3763 // Orientation
3764 mOrientationScale = 0;
3765 if (mHaveTilt) {
3766 mOrientedRanges.haveOrientation = true;
3767
3768 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3769 mOrientedRanges.orientation.source = mSource;
3770 mOrientedRanges.orientation.min = -M_PI;
3771 mOrientedRanges.orientation.max = M_PI;
3772 mOrientedRanges.orientation.flat = 0;
3773 mOrientedRanges.orientation.fuzz = 0;
3774 mOrientedRanges.orientation.resolution = 0;
3775 } else if (mCalibration.orientationCalibration !=
3776 Calibration::ORIENTATION_CALIBRATION_NONE) {
3777 if (mCalibration.orientationCalibration
3778 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3779 if (mRawPointerAxes.orientation.valid) {
3780 if (mRawPointerAxes.orientation.maxValue > 0) {
3781 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3782 } else if (mRawPointerAxes.orientation.minValue < 0) {
3783 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3784 } else {
3785 mOrientationScale = 0;
3786 }
3787 }
3788 }
3789
3790 mOrientedRanges.haveOrientation = true;
3791
3792 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3793 mOrientedRanges.orientation.source = mSource;
3794 mOrientedRanges.orientation.min = -M_PI_2;
3795 mOrientedRanges.orientation.max = M_PI_2;
3796 mOrientedRanges.orientation.flat = 0;
3797 mOrientedRanges.orientation.fuzz = 0;
3798 mOrientedRanges.orientation.resolution = 0;
3799 }
3800
3801 // Distance
3802 mDistanceScale = 0;
3803 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3804 if (mCalibration.distanceCalibration
3805 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3806 if (mCalibration.haveDistanceScale) {
3807 mDistanceScale = mCalibration.distanceScale;
3808 } else {
3809 mDistanceScale = 1.0f;
3810 }
3811 }
3812
3813 mOrientedRanges.haveDistance = true;
3814
3815 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3816 mOrientedRanges.distance.source = mSource;
3817 mOrientedRanges.distance.min =
3818 mRawPointerAxes.distance.minValue * mDistanceScale;
3819 mOrientedRanges.distance.max =
3820 mRawPointerAxes.distance.maxValue * mDistanceScale;
3821 mOrientedRanges.distance.flat = 0;
3822 mOrientedRanges.distance.fuzz =
3823 mRawPointerAxes.distance.fuzz * mDistanceScale;
3824 mOrientedRanges.distance.resolution = 0;
3825 }
3826
3827 // Compute oriented precision, scales and ranges.
3828 // Note that the maximum value reported is an inclusive maximum value so it is one
3829 // unit less than the total width or height of surface.
3830 switch (mSurfaceOrientation) {
3831 case DISPLAY_ORIENTATION_90:
3832 case DISPLAY_ORIENTATION_270:
3833 mOrientedXPrecision = mYPrecision;
3834 mOrientedYPrecision = mXPrecision;
3835
3836 mOrientedRanges.x.min = mYTranslate;
3837 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3838 mOrientedRanges.x.flat = 0;
3839 mOrientedRanges.x.fuzz = 0;
3840 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3841
3842 mOrientedRanges.y.min = mXTranslate;
3843 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3844 mOrientedRanges.y.flat = 0;
3845 mOrientedRanges.y.fuzz = 0;
3846 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3847 break;
3848
3849 default:
3850 mOrientedXPrecision = mXPrecision;
3851 mOrientedYPrecision = mYPrecision;
3852
3853 mOrientedRanges.x.min = mXTranslate;
3854 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3855 mOrientedRanges.x.flat = 0;
3856 mOrientedRanges.x.fuzz = 0;
3857 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3858
3859 mOrientedRanges.y.min = mYTranslate;
3860 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3861 mOrientedRanges.y.flat = 0;
3862 mOrientedRanges.y.fuzz = 0;
3863 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3864 break;
3865 }
3866
Jason Gerecke71b16e82014-03-10 09:47:59 -07003867 // Location
3868 updateAffineTransformation();
3869
Michael Wrightd02c5b62014-02-10 15:10:22 -08003870 if (mDeviceMode == DEVICE_MODE_POINTER) {
3871 // Compute pointer gesture detection parameters.
3872 float rawDiagonal = hypotf(rawWidth, rawHeight);
3873 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3874
3875 // Scale movements such that one whole swipe of the touch pad covers a
3876 // given area relative to the diagonal size of the display when no acceleration
3877 // is applied.
3878 // Assume that the touch pad has a square aspect ratio such that movements in
3879 // X and Y of the same number of raw units cover the same physical distance.
3880 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3881 * displayDiagonal / rawDiagonal;
3882 mPointerYMovementScale = mPointerXMovementScale;
3883
3884 // Scale zooms to cover a smaller range of the display than movements do.
3885 // This value determines the area around the pointer that is affected by freeform
3886 // pointer gestures.
3887 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3888 * displayDiagonal / rawDiagonal;
3889 mPointerYZoomScale = mPointerXZoomScale;
3890
3891 // Max width between pointers to detect a swipe gesture is more than some fraction
3892 // of the diagonal axis of the touch pad. Touches that are wider than this are
3893 // translated into freeform gestures.
3894 mPointerGestureMaxSwipeWidth =
3895 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3896
3897 // Abort current pointer usages because the state has changed.
3898 abortPointerUsage(when, 0 /*policyFlags*/);
3899 }
3900
3901 // Inform the dispatcher about the changes.
3902 *outResetNeeded = true;
3903 bumpGeneration();
3904 }
3905}
3906
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003907void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003908 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003909 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3910 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3911 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3912 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003913 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3914 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3915 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3916 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003917 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003918}
3919
3920void TouchInputMapper::configureVirtualKeys() {
3921 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3922 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3923
3924 mVirtualKeys.clear();
3925
3926 if (virtualKeyDefinitions.size() == 0) {
3927 return;
3928 }
3929
3930 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3931
3932 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3933 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003934 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3935 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003936
3937 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3938 const VirtualKeyDefinition& virtualKeyDefinition =
3939 virtualKeyDefinitions[i];
3940
3941 mVirtualKeys.add();
3942 VirtualKey& virtualKey = mVirtualKeys.editTop();
3943
3944 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3945 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003946 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003948 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3949 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003950 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3951 virtualKey.scanCode);
3952 mVirtualKeys.pop(); // drop the key
3953 continue;
3954 }
3955
3956 virtualKey.keyCode = keyCode;
3957 virtualKey.flags = flags;
3958
3959 // convert the key definition's display coordinates into touch coordinates for a hit box
3960 int32_t halfWidth = virtualKeyDefinition.width / 2;
3961 int32_t halfHeight = virtualKeyDefinition.height / 2;
3962
3963 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3964 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3965 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3966 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3967 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3968 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3969 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3970 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3971 }
3972}
3973
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003974void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003975 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003976 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977
3978 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3979 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003980 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003981 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3982 i, virtualKey.scanCode, virtualKey.keyCode,
3983 virtualKey.hitLeft, virtualKey.hitRight,
3984 virtualKey.hitTop, virtualKey.hitBottom);
3985 }
3986 }
3987}
3988
3989void TouchInputMapper::parseCalibration() {
3990 const PropertyMap& in = getDevice()->getConfiguration();
3991 Calibration& out = mCalibration;
3992
3993 // Size
3994 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3995 String8 sizeCalibrationString;
3996 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3997 if (sizeCalibrationString == "none") {
3998 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3999 } else if (sizeCalibrationString == "geometric") {
4000 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4001 } else if (sizeCalibrationString == "diameter") {
4002 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4003 } else if (sizeCalibrationString == "box") {
4004 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4005 } else if (sizeCalibrationString == "area") {
4006 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4007 } else if (sizeCalibrationString != "default") {
4008 ALOGW("Invalid value for touch.size.calibration: '%s'",
4009 sizeCalibrationString.string());
4010 }
4011 }
4012
4013 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4014 out.sizeScale);
4015 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4016 out.sizeBias);
4017 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4018 out.sizeIsSummed);
4019
4020 // Pressure
4021 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4022 String8 pressureCalibrationString;
4023 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4024 if (pressureCalibrationString == "none") {
4025 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4026 } else if (pressureCalibrationString == "physical") {
4027 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4028 } else if (pressureCalibrationString == "amplitude") {
4029 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4030 } else if (pressureCalibrationString != "default") {
4031 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4032 pressureCalibrationString.string());
4033 }
4034 }
4035
4036 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4037 out.pressureScale);
4038
4039 // Orientation
4040 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4041 String8 orientationCalibrationString;
4042 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4043 if (orientationCalibrationString == "none") {
4044 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4045 } else if (orientationCalibrationString == "interpolated") {
4046 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4047 } else if (orientationCalibrationString == "vector") {
4048 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4049 } else if (orientationCalibrationString != "default") {
4050 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4051 orientationCalibrationString.string());
4052 }
4053 }
4054
4055 // Distance
4056 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4057 String8 distanceCalibrationString;
4058 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4059 if (distanceCalibrationString == "none") {
4060 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4061 } else if (distanceCalibrationString == "scaled") {
4062 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4063 } else if (distanceCalibrationString != "default") {
4064 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4065 distanceCalibrationString.string());
4066 }
4067 }
4068
4069 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4070 out.distanceScale);
4071
4072 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4073 String8 coverageCalibrationString;
4074 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4075 if (coverageCalibrationString == "none") {
4076 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4077 } else if (coverageCalibrationString == "box") {
4078 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4079 } else if (coverageCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4081 coverageCalibrationString.string());
4082 }
4083 }
4084}
4085
4086void TouchInputMapper::resolveCalibration() {
4087 // Size
4088 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4089 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4090 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4091 }
4092 } else {
4093 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4094 }
4095
4096 // Pressure
4097 if (mRawPointerAxes.pressure.valid) {
4098 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4099 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4100 }
4101 } else {
4102 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4103 }
4104
4105 // Orientation
4106 if (mRawPointerAxes.orientation.valid) {
4107 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4108 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4109 }
4110 } else {
4111 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4112 }
4113
4114 // Distance
4115 if (mRawPointerAxes.distance.valid) {
4116 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4117 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4118 }
4119 } else {
4120 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4121 }
4122
4123 // Coverage
4124 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4125 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4126 }
4127}
4128
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004129void TouchInputMapper::dumpCalibration(std::string& dump) {
4130 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131
4132 // Size
4133 switch (mCalibration.sizeCalibration) {
4134 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 break;
4137 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004138 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004139 break;
4140 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004141 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004142 break;
4143 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004145 break;
4146 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 break;
4149 default:
4150 ALOG_ASSERT(false);
4151 }
4152
4153 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 mCalibration.sizeScale);
4156 }
4157
4158 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 mCalibration.sizeBias);
4161 }
4162
4163 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004164 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004165 toString(mCalibration.sizeIsSummed));
4166 }
4167
4168 // Pressure
4169 switch (mCalibration.pressureCalibration) {
4170 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 break;
4173 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 break;
4176 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 break;
4179 default:
4180 ALOG_ASSERT(false);
4181 }
4182
4183 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004184 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004185 mCalibration.pressureScale);
4186 }
4187
4188 // Orientation
4189 switch (mCalibration.orientationCalibration) {
4190 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 break;
4193 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 break;
4199 default:
4200 ALOG_ASSERT(false);
4201 }
4202
4203 // Distance
4204 switch (mCalibration.distanceCalibration) {
4205 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004206 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004207 break;
4208 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004209 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004210 break;
4211 default:
4212 ALOG_ASSERT(false);
4213 }
4214
4215 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004216 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004217 mCalibration.distanceScale);
4218 }
4219
4220 switch (mCalibration.coverageCalibration) {
4221 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004222 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004223 break;
4224 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004225 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004226 break;
4227 default:
4228 ALOG_ASSERT(false);
4229 }
4230}
4231
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004232void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4233 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004234
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004235 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4236 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4237 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4238 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4239 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4240 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004241}
4242
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004243void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004244 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4245 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004246}
4247
Michael Wrightd02c5b62014-02-10 15:10:22 -08004248void TouchInputMapper::reset(nsecs_t when) {
4249 mCursorButtonAccumulator.reset(getDevice());
4250 mCursorScrollAccumulator.reset(getDevice());
4251 mTouchButtonAccumulator.reset(getDevice());
4252
4253 mPointerVelocityControl.reset();
4254 mWheelXVelocityControl.reset();
4255 mWheelYVelocityControl.reset();
4256
Michael Wright842500e2015-03-13 17:32:02 -07004257 mRawStatesPending.clear();
4258 mCurrentRawState.clear();
4259 mCurrentCookedState.clear();
4260 mLastRawState.clear();
4261 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 mPointerUsage = POINTER_USAGE_NONE;
4263 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004264 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004265 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266 mDownTime = 0;
4267
4268 mCurrentVirtualKey.down = false;
4269
4270 mPointerGesture.reset();
4271 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004272 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273
Yi Kong9b14ac62018-07-17 13:48:38 -07004274 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4276 mPointerController->clearSpots();
4277 }
4278
4279 InputMapper::reset(when);
4280}
4281
Michael Wright842500e2015-03-13 17:32:02 -07004282void TouchInputMapper::resetExternalStylus() {
4283 mExternalStylusState.clear();
4284 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004285 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004286 mExternalStylusDataPending = false;
4287}
4288
Michael Wright43fd19f2015-04-21 19:02:58 +01004289void TouchInputMapper::clearStylusDataPendingFlags() {
4290 mExternalStylusDataPending = false;
4291 mExternalStylusFusionTimeout = LLONG_MAX;
4292}
4293
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004294void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4295 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4296 nsecs_t latency = now - evdevTime;
4297 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4298 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4299 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4300 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
4301 mStatistics.min, mStatistics.max, mStatistics.mean(), mStatistics.stdev());
4302 mStatistics.reset(now);
4303 }
4304}
4305
Michael Wrightd02c5b62014-02-10 15:10:22 -08004306void TouchInputMapper::process(const RawEvent* rawEvent) {
4307 mCursorButtonAccumulator.process(rawEvent);
4308 mCursorScrollAccumulator.process(rawEvent);
4309 mTouchButtonAccumulator.process(rawEvent);
4310
4311 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004312 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313 sync(rawEvent->when);
4314 }
4315}
4316
4317void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004318 const RawState* last = mRawStatesPending.isEmpty() ?
4319 &mCurrentRawState : &mRawStatesPending.top();
4320
4321 // Push a new state.
4322 mRawStatesPending.push();
4323 RawState* next = &mRawStatesPending.editTop();
4324 next->clear();
4325 next->when = when;
4326
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004328 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 | mCursorButtonAccumulator.getButtonState();
4330
Michael Wright842500e2015-03-13 17:32:02 -07004331 // Sync scroll
4332 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4333 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 mCursorScrollAccumulator.finishSync();
4335
Michael Wright842500e2015-03-13 17:32:02 -07004336 // Sync touch
4337 syncTouch(when, next);
4338
4339 // Assign pointer ids.
4340 if (!mHavePointerIds) {
4341 assignPointerIds(last, next);
4342 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004343
4344#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004345 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4346 "hovering ids 0x%08x -> 0x%08x",
4347 last->rawPointerData.pointerCount,
4348 next->rawPointerData.pointerCount,
4349 last->rawPointerData.touchingIdBits.value,
4350 next->rawPointerData.touchingIdBits.value,
4351 last->rawPointerData.hoveringIdBits.value,
4352 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353#endif
4354
Michael Wright842500e2015-03-13 17:32:02 -07004355 processRawTouches(false /*timeout*/);
4356}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004357
Michael Wright842500e2015-03-13 17:32:02 -07004358void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004359 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4360 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004361 mCurrentRawState.clear();
4362 mRawStatesPending.clear();
4363 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004364 }
4365
Michael Wright842500e2015-03-13 17:32:02 -07004366 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4367 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4368 // touching the current state will only observe the events that have been dispatched to the
4369 // rest of the pipeline.
4370 const size_t N = mRawStatesPending.size();
4371 size_t count;
4372 for(count = 0; count < N; count++) {
4373 const RawState& next = mRawStatesPending[count];
4374
4375 // A failure to assign the stylus id means that we're waiting on stylus data
4376 // and so should defer the rest of the pipeline.
4377 if (assignExternalStylusId(next, timeout)) {
4378 break;
4379 }
4380
4381 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004382 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004383 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004384 if (mCurrentRawState.when < mLastRawState.when) {
4385 mCurrentRawState.when = mLastRawState.when;
4386 }
Michael Wright842500e2015-03-13 17:32:02 -07004387 cookAndDispatch(mCurrentRawState.when);
4388 }
4389 if (count != 0) {
4390 mRawStatesPending.removeItemsAt(0, count);
4391 }
4392
Michael Wright842500e2015-03-13 17:32:02 -07004393 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004394 if (timeout) {
4395 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4396 clearStylusDataPendingFlags();
4397 mCurrentRawState.copyFrom(mLastRawState);
4398#if DEBUG_STYLUS_FUSION
4399 ALOGD("Timeout expired, synthesizing event with new stylus data");
4400#endif
4401 cookAndDispatch(when);
4402 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4403 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4404 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4405 }
Michael Wright842500e2015-03-13 17:32:02 -07004406 }
4407}
4408
4409void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4410 // Always start with a clean state.
4411 mCurrentCookedState.clear();
4412
4413 // Apply stylus buttons to current raw state.
4414 applyExternalStylusButtonState(when);
4415
4416 // Handle policy on initial down or hover events.
4417 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4418 && mCurrentRawState.rawPointerData.pointerCount != 0;
4419
4420 uint32_t policyFlags = 0;
4421 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4422 if (initialDown || buttonsPressed) {
4423 // If this is a touch screen, hide the pointer on an initial down.
4424 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4425 getContext()->fadePointer();
4426 }
4427
4428 if (mParameters.wake) {
4429 policyFlags |= POLICY_FLAG_WAKE;
4430 }
4431 }
4432
4433 // Consume raw off-screen touches before cooking pointer data.
4434 // If touches are consumed, subsequent code will not receive any pointer data.
4435 if (consumeRawTouches(when, policyFlags)) {
4436 mCurrentRawState.rawPointerData.clear();
4437 }
4438
4439 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4440 // with cooked pointer data that has the same ids and indices as the raw data.
4441 // The following code can use either the raw or cooked data, as needed.
4442 cookPointerData();
4443
4444 // Apply stylus pressure to current cooked state.
4445 applyExternalStylusTouchState(when);
4446
4447 // Synthesize key down from raw buttons if needed.
4448 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004449 mViewport.displayId, policyFlags,
4450 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004451
4452 // Dispatch the touches either directly or by translation through a pointer on screen.
4453 if (mDeviceMode == DEVICE_MODE_POINTER) {
4454 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4455 !idBits.isEmpty(); ) {
4456 uint32_t id = idBits.clearFirstMarkedBit();
4457 const RawPointerData::Pointer& pointer =
4458 mCurrentRawState.rawPointerData.pointerForId(id);
4459 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4460 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4461 mCurrentCookedState.stylusIdBits.markBit(id);
4462 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4463 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4464 mCurrentCookedState.fingerIdBits.markBit(id);
4465 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4466 mCurrentCookedState.mouseIdBits.markBit(id);
4467 }
4468 }
4469 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4470 !idBits.isEmpty(); ) {
4471 uint32_t id = idBits.clearFirstMarkedBit();
4472 const RawPointerData::Pointer& pointer =
4473 mCurrentRawState.rawPointerData.pointerForId(id);
4474 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4475 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4476 mCurrentCookedState.stylusIdBits.markBit(id);
4477 }
4478 }
4479
4480 // Stylus takes precedence over all tools, then mouse, then finger.
4481 PointerUsage pointerUsage = mPointerUsage;
4482 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4483 mCurrentCookedState.mouseIdBits.clear();
4484 mCurrentCookedState.fingerIdBits.clear();
4485 pointerUsage = POINTER_USAGE_STYLUS;
4486 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4487 mCurrentCookedState.fingerIdBits.clear();
4488 pointerUsage = POINTER_USAGE_MOUSE;
4489 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4490 isPointerDown(mCurrentRawState.buttonState)) {
4491 pointerUsage = POINTER_USAGE_GESTURES;
4492 }
4493
4494 dispatchPointerUsage(when, policyFlags, pointerUsage);
4495 } else {
4496 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004497 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004498 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4499 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4500
4501 mPointerController->setButtonState(mCurrentRawState.buttonState);
4502 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4503 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004504 mCurrentCookedState.cookedPointerData.touchingIdBits,
4505 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004506 }
4507
Michael Wright8e812822015-06-22 16:18:21 +01004508 if (!mCurrentMotionAborted) {
4509 dispatchButtonRelease(when, policyFlags);
4510 dispatchHoverExit(when, policyFlags);
4511 dispatchTouches(when, policyFlags);
4512 dispatchHoverEnterAndMove(when, policyFlags);
4513 dispatchButtonPress(when, policyFlags);
4514 }
4515
4516 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4517 mCurrentMotionAborted = false;
4518 }
Michael Wright842500e2015-03-13 17:32:02 -07004519 }
4520
4521 // Synthesize key up from raw buttons if needed.
4522 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004523 mViewport.displayId, policyFlags,
4524 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004525
4526 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004527 mCurrentRawState.rawVScroll = 0;
4528 mCurrentRawState.rawHScroll = 0;
4529
4530 // Copy current touch to last touch in preparation for the next cycle.
4531 mLastRawState.copyFrom(mCurrentRawState);
4532 mLastCookedState.copyFrom(mCurrentCookedState);
4533}
4534
4535void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004536 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004537 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4538 }
4539}
4540
4541void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004542 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4543 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004544
Michael Wright53dca3a2015-04-23 17:39:53 +01004545 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4546 float pressure = mExternalStylusState.pressure;
4547 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4548 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4549 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4550 }
4551 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4552 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4553
4554 PointerProperties& properties =
4555 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004556 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4557 properties.toolType = mExternalStylusState.toolType;
4558 }
4559 }
4560}
4561
4562bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4563 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4564 return false;
4565 }
4566
4567 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4568 && state.rawPointerData.pointerCount != 0;
4569 if (initialDown) {
4570 if (mExternalStylusState.pressure != 0.0f) {
4571#if DEBUG_STYLUS_FUSION
4572 ALOGD("Have both stylus and touch data, beginning fusion");
4573#endif
4574 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4575 } else if (timeout) {
4576#if DEBUG_STYLUS_FUSION
4577 ALOGD("Timeout expired, assuming touch is not a stylus.");
4578#endif
4579 resetExternalStylus();
4580 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004581 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4582 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004583 }
4584#if DEBUG_STYLUS_FUSION
4585 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004586 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004587#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004588 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004589 return true;
4590 }
4591 }
4592
4593 // Check if the stylus pointer has gone up.
4594 if (mExternalStylusId != -1 &&
4595 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4596#if DEBUG_STYLUS_FUSION
4597 ALOGD("Stylus pointer is going up");
4598#endif
4599 mExternalStylusId = -1;
4600 }
4601
4602 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603}
4604
4605void TouchInputMapper::timeoutExpired(nsecs_t when) {
4606 if (mDeviceMode == DEVICE_MODE_POINTER) {
4607 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4608 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4609 }
Michael Wright842500e2015-03-13 17:32:02 -07004610 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004611 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004612 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004613 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4614 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004615 }
4616 }
4617}
4618
4619void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004620 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004621 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004622 // We're either in the middle of a fused stream of data or we're waiting on data before
4623 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4624 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004625 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004626 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004627 }
4628}
4629
4630bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4631 // Check for release of a virtual key.
4632 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004633 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 // Pointer went up while virtual key was down.
4635 mCurrentVirtualKey.down = false;
4636 if (!mCurrentVirtualKey.ignored) {
4637#if DEBUG_VIRTUAL_KEYS
4638 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4639 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4640#endif
4641 dispatchVirtualKey(when, policyFlags,
4642 AKEY_EVENT_ACTION_UP,
4643 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4644 }
4645 return true;
4646 }
4647
Michael Wright842500e2015-03-13 17:32:02 -07004648 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4649 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4650 const RawPointerData::Pointer& pointer =
4651 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4653 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4654 // Pointer is still within the space of the virtual key.
4655 return true;
4656 }
4657 }
4658
4659 // Pointer left virtual key area or another pointer also went down.
4660 // Send key cancellation but do not consume the touch yet.
4661 // This is useful when the user swipes through from the virtual key area
4662 // into the main display surface.
4663 mCurrentVirtualKey.down = false;
4664 if (!mCurrentVirtualKey.ignored) {
4665#if DEBUG_VIRTUAL_KEYS
4666 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4667 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4668#endif
4669 dispatchVirtualKey(when, policyFlags,
4670 AKEY_EVENT_ACTION_UP,
4671 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4672 | AKEY_EVENT_FLAG_CANCELED);
4673 }
4674 }
4675
Michael Wright842500e2015-03-13 17:32:02 -07004676 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4677 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004679 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4680 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4682 // If exactly one pointer went down, check for virtual key hit.
4683 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004684 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4686 if (virtualKey) {
4687 mCurrentVirtualKey.down = true;
4688 mCurrentVirtualKey.downTime = when;
4689 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4690 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4691 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4692 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4693
4694 if (!mCurrentVirtualKey.ignored) {
4695#if DEBUG_VIRTUAL_KEYS
4696 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4697 mCurrentVirtualKey.keyCode,
4698 mCurrentVirtualKey.scanCode);
4699#endif
4700 dispatchVirtualKey(when, policyFlags,
4701 AKEY_EVENT_ACTION_DOWN,
4702 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4703 }
4704 }
4705 }
4706 return true;
4707 }
4708 }
4709
4710 // Disable all virtual key touches that happen within a short time interval of the
4711 // most recent touch within the screen area. The idea is to filter out stray
4712 // virtual key presses when interacting with the touch screen.
4713 //
4714 // Problems we're trying to solve:
4715 //
4716 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4717 // virtual key area that is implemented by a separate touch panel and accidentally
4718 // triggers a virtual key.
4719 //
4720 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4721 // area and accidentally triggers a virtual key. This often happens when virtual keys
4722 // are layed out below the screen near to where the on screen keyboard's space bar
4723 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004724 if (mConfig.virtualKeyQuietTime > 0 &&
4725 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4727 }
4728 return false;
4729}
4730
4731void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4732 int32_t keyEventAction, int32_t keyEventFlags) {
4733 int32_t keyCode = mCurrentVirtualKey.keyCode;
4734 int32_t scanCode = mCurrentVirtualKey.scanCode;
4735 nsecs_t downTime = mCurrentVirtualKey.downTime;
4736 int32_t metaState = mContext->getGlobalMetaState();
4737 policyFlags |= POLICY_FLAG_VIRTUAL;
4738
Prabir Pradhan42611e02018-11-27 14:04:02 -08004739 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4740 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004741 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004742 getListener()->notifyKey(&args);
4743}
4744
Michael Wright8e812822015-06-22 16:18:21 +01004745void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4746 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4747 if (!currentIdBits.isEmpty()) {
4748 int32_t metaState = getContext()->getGlobalMetaState();
4749 int32_t buttonState = mCurrentCookedState.buttonState;
4750 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4751 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004752 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004753 mCurrentCookedState.cookedPointerData.pointerProperties,
4754 mCurrentCookedState.cookedPointerData.pointerCoords,
4755 mCurrentCookedState.cookedPointerData.idToIndex,
4756 currentIdBits, -1,
4757 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4758 mCurrentMotionAborted = true;
4759 }
4760}
4761
Michael Wrightd02c5b62014-02-10 15:10:22 -08004762void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004763 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4764 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004765 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004766 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004767
4768 if (currentIdBits == lastIdBits) {
4769 if (!currentIdBits.isEmpty()) {
4770 // No pointer id changes so this is a move event.
4771 // The listener takes care of batching moves so we don't have to deal with that here.
4772 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004773 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004774 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004775 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004776 mCurrentCookedState.cookedPointerData.pointerProperties,
4777 mCurrentCookedState.cookedPointerData.pointerCoords,
4778 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 currentIdBits, -1,
4780 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4781 }
4782 } else {
4783 // There may be pointers going up and pointers going down and pointers moving
4784 // all at the same time.
4785 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4786 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4787 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4788 BitSet32 dispatchedIdBits(lastIdBits.value);
4789
4790 // Update last coordinates of pointers that have moved so that we observe the new
4791 // pointer positions at the same time as other pointers that have just gone up.
4792 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004793 mCurrentCookedState.cookedPointerData.pointerProperties,
4794 mCurrentCookedState.cookedPointerData.pointerCoords,
4795 mCurrentCookedState.cookedPointerData.idToIndex,
4796 mLastCookedState.cookedPointerData.pointerProperties,
4797 mLastCookedState.cookedPointerData.pointerCoords,
4798 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004800 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004801 moveNeeded = true;
4802 }
4803
4804 // Dispatch pointer up events.
4805 while (!upIdBits.isEmpty()) {
4806 uint32_t upId = upIdBits.clearFirstMarkedBit();
4807
4808 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004809 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004810 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004811 mLastCookedState.cookedPointerData.pointerProperties,
4812 mLastCookedState.cookedPointerData.pointerCoords,
4813 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004814 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004815 dispatchedIdBits.clearBit(upId);
4816 }
4817
4818 // Dispatch move events if any of the remaining pointers moved from their old locations.
4819 // Although applications receive new locations as part of individual pointer up
4820 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004821 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4823 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004824 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004825 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004826 mCurrentCookedState.cookedPointerData.pointerProperties,
4827 mCurrentCookedState.cookedPointerData.pointerCoords,
4828 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004829 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 }
4831
4832 // Dispatch pointer down events using the new pointer locations.
4833 while (!downIdBits.isEmpty()) {
4834 uint32_t downId = downIdBits.clearFirstMarkedBit();
4835 dispatchedIdBits.markBit(downId);
4836
4837 if (dispatchedIdBits.count() == 1) {
4838 // First pointer is going down. Set down time.
4839 mDownTime = when;
4840 }
4841
4842 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004843 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004844 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004845 mCurrentCookedState.cookedPointerData.pointerProperties,
4846 mCurrentCookedState.cookedPointerData.pointerCoords,
4847 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004848 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004849 }
4850 }
4851}
4852
4853void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4854 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004855 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4856 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004857 int32_t metaState = getContext()->getGlobalMetaState();
4858 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004859 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004860 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004861 mLastCookedState.cookedPointerData.pointerProperties,
4862 mLastCookedState.cookedPointerData.pointerCoords,
4863 mLastCookedState.cookedPointerData.idToIndex,
4864 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004865 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4866 mSentHoverEnter = false;
4867 }
4868}
4869
4870void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004871 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4872 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 int32_t metaState = getContext()->getGlobalMetaState();
4874 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004875 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004876 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004877 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004878 mCurrentCookedState.cookedPointerData.pointerProperties,
4879 mCurrentCookedState.cookedPointerData.pointerCoords,
4880 mCurrentCookedState.cookedPointerData.idToIndex,
4881 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004882 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4883 mSentHoverEnter = true;
4884 }
4885
4886 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004887 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004888 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004889 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004890 mCurrentCookedState.cookedPointerData.pointerProperties,
4891 mCurrentCookedState.cookedPointerData.pointerCoords,
4892 mCurrentCookedState.cookedPointerData.idToIndex,
4893 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004894 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4895 }
4896}
4897
Michael Wright7b159c92015-05-14 14:48:03 +01004898void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4899 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4900 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4901 const int32_t metaState = getContext()->getGlobalMetaState();
4902 int32_t buttonState = mLastCookedState.buttonState;
4903 while (!releasedButtons.isEmpty()) {
4904 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4905 buttonState &= ~actionButton;
4906 dispatchMotion(when, policyFlags, mSource,
4907 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4908 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004909 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004910 mCurrentCookedState.cookedPointerData.pointerProperties,
4911 mCurrentCookedState.cookedPointerData.pointerCoords,
4912 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4913 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4914 }
4915}
4916
4917void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4918 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4919 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4920 const int32_t metaState = getContext()->getGlobalMetaState();
4921 int32_t buttonState = mLastCookedState.buttonState;
4922 while (!pressedButtons.isEmpty()) {
4923 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4924 buttonState |= actionButton;
4925 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4926 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004927 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004928 mCurrentCookedState.cookedPointerData.pointerProperties,
4929 mCurrentCookedState.cookedPointerData.pointerCoords,
4930 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4931 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4932 }
4933}
4934
4935const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4936 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4937 return cookedPointerData.touchingIdBits;
4938 }
4939 return cookedPointerData.hoveringIdBits;
4940}
4941
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004943 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004944
Michael Wright842500e2015-03-13 17:32:02 -07004945 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004946 mCurrentCookedState.deviceTimestamp =
4947 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004948 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4949 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4950 mCurrentRawState.rawPointerData.hoveringIdBits;
4951 mCurrentCookedState.cookedPointerData.touchingIdBits =
4952 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004953
Michael Wright7b159c92015-05-14 14:48:03 +01004954 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4955 mCurrentCookedState.buttonState = 0;
4956 } else {
4957 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4958 }
4959
Michael Wrightd02c5b62014-02-10 15:10:22 -08004960 // Walk through the the active pointers and map device coordinates onto
4961 // surface coordinates and adjust for display orientation.
4962 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004963 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004964
4965 // Size
4966 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4967 switch (mCalibration.sizeCalibration) {
4968 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4969 case Calibration::SIZE_CALIBRATION_DIAMETER:
4970 case Calibration::SIZE_CALIBRATION_BOX:
4971 case Calibration::SIZE_CALIBRATION_AREA:
4972 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4973 touchMajor = in.touchMajor;
4974 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4975 toolMajor = in.toolMajor;
4976 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4977 size = mRawPointerAxes.touchMinor.valid
4978 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4979 } else if (mRawPointerAxes.touchMajor.valid) {
4980 toolMajor = touchMajor = in.touchMajor;
4981 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4982 ? in.touchMinor : in.touchMajor;
4983 size = mRawPointerAxes.touchMinor.valid
4984 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4985 } else if (mRawPointerAxes.toolMajor.valid) {
4986 touchMajor = toolMajor = in.toolMajor;
4987 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4988 ? in.toolMinor : in.toolMajor;
4989 size = mRawPointerAxes.toolMinor.valid
4990 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4991 } else {
4992 ALOG_ASSERT(false, "No touch or tool axes. "
4993 "Size calibration should have been resolved to NONE.");
4994 touchMajor = 0;
4995 touchMinor = 0;
4996 toolMajor = 0;
4997 toolMinor = 0;
4998 size = 0;
4999 }
5000
5001 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005002 uint32_t touchingCount =
5003 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005004 if (touchingCount > 1) {
5005 touchMajor /= touchingCount;
5006 touchMinor /= touchingCount;
5007 toolMajor /= touchingCount;
5008 toolMinor /= touchingCount;
5009 size /= touchingCount;
5010 }
5011 }
5012
5013 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5014 touchMajor *= mGeometricScale;
5015 touchMinor *= mGeometricScale;
5016 toolMajor *= mGeometricScale;
5017 toolMinor *= mGeometricScale;
5018 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5019 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5020 touchMinor = touchMajor;
5021 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5022 toolMinor = toolMajor;
5023 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5024 touchMinor = touchMajor;
5025 toolMinor = toolMajor;
5026 }
5027
5028 mCalibration.applySizeScaleAndBias(&touchMajor);
5029 mCalibration.applySizeScaleAndBias(&touchMinor);
5030 mCalibration.applySizeScaleAndBias(&toolMajor);
5031 mCalibration.applySizeScaleAndBias(&toolMinor);
5032 size *= mSizeScale;
5033 break;
5034 default:
5035 touchMajor = 0;
5036 touchMinor = 0;
5037 toolMajor = 0;
5038 toolMinor = 0;
5039 size = 0;
5040 break;
5041 }
5042
5043 // Pressure
5044 float pressure;
5045 switch (mCalibration.pressureCalibration) {
5046 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5047 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5048 pressure = in.pressure * mPressureScale;
5049 break;
5050 default:
5051 pressure = in.isHovering ? 0 : 1;
5052 break;
5053 }
5054
5055 // Tilt and Orientation
5056 float tilt;
5057 float orientation;
5058 if (mHaveTilt) {
5059 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5060 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5061 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5062 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5063 } else {
5064 tilt = 0;
5065
5066 switch (mCalibration.orientationCalibration) {
5067 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5068 orientation = in.orientation * mOrientationScale;
5069 break;
5070 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5071 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5072 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5073 if (c1 != 0 || c2 != 0) {
5074 orientation = atan2f(c1, c2) * 0.5f;
5075 float confidence = hypotf(c1, c2);
5076 float scale = 1.0f + confidence / 16.0f;
5077 touchMajor *= scale;
5078 touchMinor /= scale;
5079 toolMajor *= scale;
5080 toolMinor /= scale;
5081 } else {
5082 orientation = 0;
5083 }
5084 break;
5085 }
5086 default:
5087 orientation = 0;
5088 }
5089 }
5090
5091 // Distance
5092 float distance;
5093 switch (mCalibration.distanceCalibration) {
5094 case Calibration::DISTANCE_CALIBRATION_SCALED:
5095 distance = in.distance * mDistanceScale;
5096 break;
5097 default:
5098 distance = 0;
5099 }
5100
5101 // Coverage
5102 int32_t rawLeft, rawTop, rawRight, rawBottom;
5103 switch (mCalibration.coverageCalibration) {
5104 case Calibration::COVERAGE_CALIBRATION_BOX:
5105 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5106 rawRight = in.toolMinor & 0x0000ffff;
5107 rawBottom = in.toolMajor & 0x0000ffff;
5108 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5109 break;
5110 default:
5111 rawLeft = rawTop = rawRight = rawBottom = 0;
5112 break;
5113 }
5114
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005115 // Adjust X,Y coords for device calibration
5116 // TODO: Adjust coverage coords?
5117 float xTransformed = in.x, yTransformed = in.y;
5118 mAffineTransform.applyTo(xTransformed, yTransformed);
5119
5120 // Adjust X, Y, and coverage coords for surface orientation.
5121 float x, y;
5122 float left, top, right, bottom;
5123
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 switch (mSurfaceOrientation) {
5125 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005126 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5127 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5129 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5130 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5131 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5132 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005133 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005134 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5135 }
5136 break;
5137 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005138 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005139 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005140 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5141 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5143 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5144 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005145 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5147 }
5148 break;
5149 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005150 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005151 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005152 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5153 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005154 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5155 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5156 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005157 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005158 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5159 }
5160 break;
5161 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005162 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5163 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005164 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5165 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5166 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5167 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5168 break;
5169 }
5170
5171 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005172 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 out.clear();
5174 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5175 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5176 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5177 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5178 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5179 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5180 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5181 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5182 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5183 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5184 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5185 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5186 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5187 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5188 } else {
5189 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5190 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5191 }
5192
5193 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005194 PointerProperties& properties =
5195 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005196 uint32_t id = in.id;
5197 properties.clear();
5198 properties.id = id;
5199 properties.toolType = in.toolType;
5200
5201 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005202 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 }
5204}
5205
5206void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5207 PointerUsage pointerUsage) {
5208 if (pointerUsage != mPointerUsage) {
5209 abortPointerUsage(when, policyFlags);
5210 mPointerUsage = pointerUsage;
5211 }
5212
5213 switch (mPointerUsage) {
5214 case POINTER_USAGE_GESTURES:
5215 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5216 break;
5217 case POINTER_USAGE_STYLUS:
5218 dispatchPointerStylus(when, policyFlags);
5219 break;
5220 case POINTER_USAGE_MOUSE:
5221 dispatchPointerMouse(when, policyFlags);
5222 break;
5223 default:
5224 break;
5225 }
5226}
5227
5228void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5229 switch (mPointerUsage) {
5230 case POINTER_USAGE_GESTURES:
5231 abortPointerGestures(when, policyFlags);
5232 break;
5233 case POINTER_USAGE_STYLUS:
5234 abortPointerStylus(when, policyFlags);
5235 break;
5236 case POINTER_USAGE_MOUSE:
5237 abortPointerMouse(when, policyFlags);
5238 break;
5239 default:
5240 break;
5241 }
5242
5243 mPointerUsage = POINTER_USAGE_NONE;
5244}
5245
5246void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5247 bool isTimeout) {
5248 // Update current gesture coordinates.
5249 bool cancelPreviousGesture, finishPreviousGesture;
5250 bool sendEvents = preparePointerGestures(when,
5251 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5252 if (!sendEvents) {
5253 return;
5254 }
5255 if (finishPreviousGesture) {
5256 cancelPreviousGesture = false;
5257 }
5258
5259 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005260 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5261 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005262 if (finishPreviousGesture || cancelPreviousGesture) {
5263 mPointerController->clearSpots();
5264 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005265
5266 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5267 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5268 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005269 mPointerGesture.currentGestureIdBits,
5270 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005271 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005272 } else {
5273 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5274 }
5275
5276 // Show or hide the pointer if needed.
5277 switch (mPointerGesture.currentGestureMode) {
5278 case PointerGesture::NEUTRAL:
5279 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005280 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5281 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 // Remind the user of where the pointer is after finishing a gesture with spots.
5283 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5284 }
5285 break;
5286 case PointerGesture::TAP:
5287 case PointerGesture::TAP_DRAG:
5288 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5289 case PointerGesture::HOVER:
5290 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005291 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005292 // Unfade the pointer when the current gesture manipulates the
5293 // area directly under the pointer.
5294 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5295 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 case PointerGesture::FREEFORM:
5297 // Fade the pointer when the current gesture manipulates a different
5298 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005299 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005300 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5301 } else {
5302 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5303 }
5304 break;
5305 }
5306
5307 // Send events!
5308 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005309 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310
5311 // Update last coordinates of pointers that have moved so that we observe the new
5312 // pointer positions at the same time as other pointers that have just gone up.
5313 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5314 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5315 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5316 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5317 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5318 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5319 bool moveNeeded = false;
5320 if (down && !cancelPreviousGesture && !finishPreviousGesture
5321 && !mPointerGesture.lastGestureIdBits.isEmpty()
5322 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5323 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5324 & mPointerGesture.lastGestureIdBits.value);
5325 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5326 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5327 mPointerGesture.lastGestureProperties,
5328 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5329 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005330 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 moveNeeded = true;
5332 }
5333 }
5334
5335 // Send motion events for all pointers that went up or were canceled.
5336 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5337 if (!dispatchedGestureIdBits.isEmpty()) {
5338 if (cancelPreviousGesture) {
5339 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005340 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005341 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 mPointerGesture.lastGestureProperties,
5343 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005344 dispatchedGestureIdBits, -1, 0,
5345 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346
5347 dispatchedGestureIdBits.clear();
5348 } else {
5349 BitSet32 upGestureIdBits;
5350 if (finishPreviousGesture) {
5351 upGestureIdBits = dispatchedGestureIdBits;
5352 } else {
5353 upGestureIdBits.value = dispatchedGestureIdBits.value
5354 & ~mPointerGesture.currentGestureIdBits.value;
5355 }
5356 while (!upGestureIdBits.isEmpty()) {
5357 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5358
5359 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005360 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005362 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005363 mPointerGesture.lastGestureProperties,
5364 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5365 dispatchedGestureIdBits, id,
5366 0, 0, mPointerGesture.downTime);
5367
5368 dispatchedGestureIdBits.clearBit(id);
5369 }
5370 }
5371 }
5372
5373 // Send motion events for all pointers that moved.
5374 if (moveNeeded) {
5375 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005376 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005377 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 mPointerGesture.currentGestureProperties,
5379 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5380 dispatchedGestureIdBits, -1,
5381 0, 0, mPointerGesture.downTime);
5382 }
5383
5384 // Send motion events for all pointers that went down.
5385 if (down) {
5386 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5387 & ~dispatchedGestureIdBits.value);
5388 while (!downGestureIdBits.isEmpty()) {
5389 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5390 dispatchedGestureIdBits.markBit(id);
5391
5392 if (dispatchedGestureIdBits.count() == 1) {
5393 mPointerGesture.downTime = when;
5394 }
5395
5396 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005397 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005398 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005399 mPointerGesture.currentGestureProperties,
5400 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5401 dispatchedGestureIdBits, id,
5402 0, 0, mPointerGesture.downTime);
5403 }
5404 }
5405
5406 // Send motion events for hover.
5407 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5408 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005409 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005410 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 mPointerGesture.currentGestureProperties,
5412 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5413 mPointerGesture.currentGestureIdBits, -1,
5414 0, 0, mPointerGesture.downTime);
5415 } else if (dispatchedGestureIdBits.isEmpty()
5416 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5417 // Synthesize a hover move event after all pointers go up to indicate that
5418 // the pointer is hovering again even if the user is not currently touching
5419 // the touch pad. This ensures that a view will receive a fresh hover enter
5420 // event after a tap.
5421 float x, y;
5422 mPointerController->getPosition(&x, &y);
5423
5424 PointerProperties pointerProperties;
5425 pointerProperties.clear();
5426 pointerProperties.id = 0;
5427 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5428
5429 PointerCoords pointerCoords;
5430 pointerCoords.clear();
5431 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5432 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5433
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005434 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005435 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005436 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005437 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005438 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005439 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005440 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005441 getListener()->notifyMotion(&args);
5442 }
5443
5444 // Update state.
5445 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5446 if (!down) {
5447 mPointerGesture.lastGestureIdBits.clear();
5448 } else {
5449 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5450 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5451 uint32_t id = idBits.clearFirstMarkedBit();
5452 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5453 mPointerGesture.lastGestureProperties[index].copyFrom(
5454 mPointerGesture.currentGestureProperties[index]);
5455 mPointerGesture.lastGestureCoords[index].copyFrom(
5456 mPointerGesture.currentGestureCoords[index]);
5457 mPointerGesture.lastGestureIdToIndex[id] = index;
5458 }
5459 }
5460}
5461
5462void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5463 // Cancel previously dispatches pointers.
5464 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5465 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005466 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005467 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005468 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005469 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005470 mPointerGesture.lastGestureProperties,
5471 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5472 mPointerGesture.lastGestureIdBits, -1,
5473 0, 0, mPointerGesture.downTime);
5474 }
5475
5476 // Reset the current pointer gesture.
5477 mPointerGesture.reset();
5478 mPointerVelocityControl.reset();
5479
5480 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005481 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5483 mPointerController->clearSpots();
5484 }
5485}
5486
5487bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5488 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5489 *outCancelPreviousGesture = false;
5490 *outFinishPreviousGesture = false;
5491
5492 // Handle TAP timeout.
5493 if (isTimeout) {
5494#if DEBUG_GESTURES
5495 ALOGD("Gestures: Processing timeout");
5496#endif
5497
5498 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5499 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5500 // The tap/drag timeout has not yet expired.
5501 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5502 + mConfig.pointerGestureTapDragInterval);
5503 } else {
5504 // The tap is finished.
5505#if DEBUG_GESTURES
5506 ALOGD("Gestures: TAP finished");
5507#endif
5508 *outFinishPreviousGesture = true;
5509
5510 mPointerGesture.activeGestureId = -1;
5511 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5512 mPointerGesture.currentGestureIdBits.clear();
5513
5514 mPointerVelocityControl.reset();
5515 return true;
5516 }
5517 }
5518
5519 // We did not handle this timeout.
5520 return false;
5521 }
5522
Michael Wright842500e2015-03-13 17:32:02 -07005523 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5524 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525
5526 // Update the velocity tracker.
5527 {
5528 VelocityTracker::Position positions[MAX_POINTERS];
5529 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005530 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005532 const RawPointerData::Pointer& pointer =
5533 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005534 positions[count].x = pointer.x * mPointerXMovementScale;
5535 positions[count].y = pointer.y * mPointerYMovementScale;
5536 }
5537 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005538 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 }
5540
5541 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5542 // to NEUTRAL, then we should not generate tap event.
5543 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5544 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5545 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5546 mPointerGesture.resetTap();
5547 }
5548
5549 // Pick a new active touch id if needed.
5550 // Choose an arbitrary pointer that just went down, if there is one.
5551 // Otherwise choose an arbitrary remaining pointer.
5552 // This guarantees we always have an active touch id when there is at least one pointer.
5553 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5555 int32_t activeTouchId = lastActiveTouchId;
5556 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005557 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005558 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005559 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005560 mPointerGesture.firstTouchTime = when;
5561 }
Michael Wright842500e2015-03-13 17:32:02 -07005562 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005563 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005564 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005565 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 } else {
5567 activeTouchId = mPointerGesture.activeTouchId = -1;
5568 }
5569 }
5570
5571 // Determine whether we are in quiet time.
5572 bool isQuietTime = false;
5573 if (activeTouchId < 0) {
5574 mPointerGesture.resetQuietTime();
5575 } else {
5576 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5577 if (!isQuietTime) {
5578 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5579 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5580 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5581 && currentFingerCount < 2) {
5582 // Enter quiet time when exiting swipe or freeform state.
5583 // This is to prevent accidentally entering the hover state and flinging the
5584 // pointer when finishing a swipe and there is still one pointer left onscreen.
5585 isQuietTime = true;
5586 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5587 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005588 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 // Enter quiet time when releasing the button and there are still two or more
5590 // fingers down. This may indicate that one finger was used to press the button
5591 // but it has not gone up yet.
5592 isQuietTime = true;
5593 }
5594 if (isQuietTime) {
5595 mPointerGesture.quietTime = when;
5596 }
5597 }
5598 }
5599
5600 // Switch states based on button and pointer state.
5601 if (isQuietTime) {
5602 // Case 1: Quiet time. (QUIET)
5603#if DEBUG_GESTURES
5604 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5605 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5606#endif
5607 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5608 *outFinishPreviousGesture = true;
5609 }
5610
5611 mPointerGesture.activeGestureId = -1;
5612 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5613 mPointerGesture.currentGestureIdBits.clear();
5614
5615 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005616 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005617 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5618 // The pointer follows the active touch point.
5619 // Emit DOWN, MOVE, UP events at the pointer location.
5620 //
5621 // Only the active touch matters; other fingers are ignored. This policy helps
5622 // to handle the case where the user places a second finger on the touch pad
5623 // to apply the necessary force to depress an integrated button below the surface.
5624 // We don't want the second finger to be delivered to applications.
5625 //
5626 // For this to work well, we need to make sure to track the pointer that is really
5627 // active. If the user first puts one finger down to click then adds another
5628 // finger to drag then the active pointer should switch to the finger that is
5629 // being dragged.
5630#if DEBUG_GESTURES
5631 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5632 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5633#endif
5634 // Reset state when just starting.
5635 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5636 *outFinishPreviousGesture = true;
5637 mPointerGesture.activeGestureId = 0;
5638 }
5639
5640 // Switch pointers if needed.
5641 // Find the fastest pointer and follow it.
5642 if (activeTouchId >= 0 && currentFingerCount > 1) {
5643 int32_t bestId = -1;
5644 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005645 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005646 uint32_t id = idBits.clearFirstMarkedBit();
5647 float vx, vy;
5648 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5649 float speed = hypotf(vx, vy);
5650 if (speed > bestSpeed) {
5651 bestId = id;
5652 bestSpeed = speed;
5653 }
5654 }
5655 }
5656 if (bestId >= 0 && bestId != activeTouchId) {
5657 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005658#if DEBUG_GESTURES
5659 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5660 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5661#endif
5662 }
5663 }
5664
Jun Mukaifa1706a2015-12-03 01:14:46 -08005665 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005666 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005667 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005668 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005669 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005670 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005671 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5672 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005673
5674 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5675 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5676
5677 // Move the pointer using a relative motion.
5678 // When using spots, the click will occur at the position of the anchor
5679 // spot and all other spots will move there.
5680 mPointerController->move(deltaX, deltaY);
5681 } else {
5682 mPointerVelocityControl.reset();
5683 }
5684
5685 float x, y;
5686 mPointerController->getPosition(&x, &y);
5687
5688 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5689 mPointerGesture.currentGestureIdBits.clear();
5690 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5691 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5692 mPointerGesture.currentGestureProperties[0].clear();
5693 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5694 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5695 mPointerGesture.currentGestureCoords[0].clear();
5696 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5697 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5698 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5699 } else if (currentFingerCount == 0) {
5700 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5701 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5702 *outFinishPreviousGesture = true;
5703 }
5704
5705 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5706 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5707 bool tapped = false;
5708 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5709 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5710 && lastFingerCount == 1) {
5711 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5712 float x, y;
5713 mPointerController->getPosition(&x, &y);
5714 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5715 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5716#if DEBUG_GESTURES
5717 ALOGD("Gestures: TAP");
5718#endif
5719
5720 mPointerGesture.tapUpTime = when;
5721 getContext()->requestTimeoutAtTime(when
5722 + mConfig.pointerGestureTapDragInterval);
5723
5724 mPointerGesture.activeGestureId = 0;
5725 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5726 mPointerGesture.currentGestureIdBits.clear();
5727 mPointerGesture.currentGestureIdBits.markBit(
5728 mPointerGesture.activeGestureId);
5729 mPointerGesture.currentGestureIdToIndex[
5730 mPointerGesture.activeGestureId] = 0;
5731 mPointerGesture.currentGestureProperties[0].clear();
5732 mPointerGesture.currentGestureProperties[0].id =
5733 mPointerGesture.activeGestureId;
5734 mPointerGesture.currentGestureProperties[0].toolType =
5735 AMOTION_EVENT_TOOL_TYPE_FINGER;
5736 mPointerGesture.currentGestureCoords[0].clear();
5737 mPointerGesture.currentGestureCoords[0].setAxisValue(
5738 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5739 mPointerGesture.currentGestureCoords[0].setAxisValue(
5740 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5741 mPointerGesture.currentGestureCoords[0].setAxisValue(
5742 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5743
5744 tapped = true;
5745 } else {
5746#if DEBUG_GESTURES
5747 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5748 x - mPointerGesture.tapX,
5749 y - mPointerGesture.tapY);
5750#endif
5751 }
5752 } else {
5753#if DEBUG_GESTURES
5754 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5755 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5756 (when - mPointerGesture.tapDownTime) * 0.000001f);
5757 } else {
5758 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5759 }
5760#endif
5761 }
5762 }
5763
5764 mPointerVelocityControl.reset();
5765
5766 if (!tapped) {
5767#if DEBUG_GESTURES
5768 ALOGD("Gestures: NEUTRAL");
5769#endif
5770 mPointerGesture.activeGestureId = -1;
5771 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5772 mPointerGesture.currentGestureIdBits.clear();
5773 }
5774 } else if (currentFingerCount == 1) {
5775 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5776 // The pointer follows the active touch point.
5777 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5778 // When in TAP_DRAG, emit MOVE events at the pointer location.
5779 ALOG_ASSERT(activeTouchId >= 0);
5780
5781 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5782 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5783 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5784 float x, y;
5785 mPointerController->getPosition(&x, &y);
5786 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5787 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5788 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5789 } else {
5790#if DEBUG_GESTURES
5791 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5792 x - mPointerGesture.tapX,
5793 y - mPointerGesture.tapY);
5794#endif
5795 }
5796 } else {
5797#if DEBUG_GESTURES
5798 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5799 (when - mPointerGesture.tapUpTime) * 0.000001f);
5800#endif
5801 }
5802 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5803 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5804 }
5805
Jun Mukaifa1706a2015-12-03 01:14:46 -08005806 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005807 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005808 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005809 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005810 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005811 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005812 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5813 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814
5815 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5816 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5817
5818 // Move the pointer using a relative motion.
5819 // When using spots, the hover or drag will occur at the position of the anchor spot.
5820 mPointerController->move(deltaX, deltaY);
5821 } else {
5822 mPointerVelocityControl.reset();
5823 }
5824
5825 bool down;
5826 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5827#if DEBUG_GESTURES
5828 ALOGD("Gestures: TAP_DRAG");
5829#endif
5830 down = true;
5831 } else {
5832#if DEBUG_GESTURES
5833 ALOGD("Gestures: HOVER");
5834#endif
5835 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5836 *outFinishPreviousGesture = true;
5837 }
5838 mPointerGesture.activeGestureId = 0;
5839 down = false;
5840 }
5841
5842 float x, y;
5843 mPointerController->getPosition(&x, &y);
5844
5845 mPointerGesture.currentGestureIdBits.clear();
5846 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5847 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5848 mPointerGesture.currentGestureProperties[0].clear();
5849 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5850 mPointerGesture.currentGestureProperties[0].toolType =
5851 AMOTION_EVENT_TOOL_TYPE_FINGER;
5852 mPointerGesture.currentGestureCoords[0].clear();
5853 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5854 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5855 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5856 down ? 1.0f : 0.0f);
5857
5858 if (lastFingerCount == 0 && currentFingerCount != 0) {
5859 mPointerGesture.resetTap();
5860 mPointerGesture.tapDownTime = when;
5861 mPointerGesture.tapX = x;
5862 mPointerGesture.tapY = y;
5863 }
5864 } else {
5865 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5866 // We need to provide feedback for each finger that goes down so we cannot wait
5867 // for the fingers to move before deciding what to do.
5868 //
5869 // The ambiguous case is deciding what to do when there are two fingers down but they
5870 // have not moved enough to determine whether they are part of a drag or part of a
5871 // freeform gesture, or just a press or long-press at the pointer location.
5872 //
5873 // When there are two fingers we start with the PRESS hypothesis and we generate a
5874 // down at the pointer location.
5875 //
5876 // When the two fingers move enough or when additional fingers are added, we make
5877 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5878 ALOG_ASSERT(activeTouchId >= 0);
5879
5880 bool settled = when >= mPointerGesture.firstTouchTime
5881 + mConfig.pointerGestureMultitouchSettleInterval;
5882 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5883 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5884 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5885 *outFinishPreviousGesture = true;
5886 } else if (!settled && currentFingerCount > lastFingerCount) {
5887 // Additional pointers have gone down but not yet settled.
5888 // Reset the gesture.
5889#if DEBUG_GESTURES
5890 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5891 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5892 + mConfig.pointerGestureMultitouchSettleInterval - when)
5893 * 0.000001f);
5894#endif
5895 *outCancelPreviousGesture = true;
5896 } else {
5897 // Continue previous gesture.
5898 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5899 }
5900
5901 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5902 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5903 mPointerGesture.activeGestureId = 0;
5904 mPointerGesture.referenceIdBits.clear();
5905 mPointerVelocityControl.reset();
5906
5907 // Use the centroid and pointer location as the reference points for the gesture.
5908#if DEBUG_GESTURES
5909 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5910 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5911 + mConfig.pointerGestureMultitouchSettleInterval - when)
5912 * 0.000001f);
5913#endif
Michael Wright842500e2015-03-13 17:32:02 -07005914 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915 &mPointerGesture.referenceTouchX,
5916 &mPointerGesture.referenceTouchY);
5917 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5918 &mPointerGesture.referenceGestureY);
5919 }
5920
5921 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005922 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5924 uint32_t id = idBits.clearFirstMarkedBit();
5925 mPointerGesture.referenceDeltas[id].dx = 0;
5926 mPointerGesture.referenceDeltas[id].dy = 0;
5927 }
Michael Wright842500e2015-03-13 17:32:02 -07005928 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005929
5930 // Add delta for all fingers and calculate a common movement delta.
5931 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005932 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5933 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5935 bool first = (idBits == commonIdBits);
5936 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005937 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5938 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005939 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5940 delta.dx += cpd.x - lpd.x;
5941 delta.dy += cpd.y - lpd.y;
5942
5943 if (first) {
5944 commonDeltaX = delta.dx;
5945 commonDeltaY = delta.dy;
5946 } else {
5947 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5948 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5949 }
5950 }
5951
5952 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5953 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5954 float dist[MAX_POINTER_ID + 1];
5955 int32_t distOverThreshold = 0;
5956 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5957 uint32_t id = idBits.clearFirstMarkedBit();
5958 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5959 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5960 delta.dy * mPointerYZoomScale);
5961 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5962 distOverThreshold += 1;
5963 }
5964 }
5965
5966 // Only transition when at least two pointers have moved further than
5967 // the minimum distance threshold.
5968 if (distOverThreshold >= 2) {
5969 if (currentFingerCount > 2) {
5970 // There are more than two pointers, switch to FREEFORM.
5971#if DEBUG_GESTURES
5972 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5973 currentFingerCount);
5974#endif
5975 *outCancelPreviousGesture = true;
5976 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5977 } else {
5978 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005979 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005980 uint32_t id1 = idBits.clearFirstMarkedBit();
5981 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005982 const RawPointerData::Pointer& p1 =
5983 mCurrentRawState.rawPointerData.pointerForId(id1);
5984 const RawPointerData::Pointer& p2 =
5985 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005986 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5987 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5988 // There are two pointers but they are too far apart for a SWIPE,
5989 // switch to FREEFORM.
5990#if DEBUG_GESTURES
5991 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5992 mutualDistance, mPointerGestureMaxSwipeWidth);
5993#endif
5994 *outCancelPreviousGesture = true;
5995 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5996 } else {
5997 // There are two pointers. Wait for both pointers to start moving
5998 // before deciding whether this is a SWIPE or FREEFORM gesture.
5999 float dist1 = dist[id1];
6000 float dist2 = dist[id2];
6001 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6002 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6003 // Calculate the dot product of the displacement vectors.
6004 // When the vectors are oriented in approximately the same direction,
6005 // the angle betweeen them is near zero and the cosine of the angle
6006 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6007 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6008 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6009 float dx1 = delta1.dx * mPointerXZoomScale;
6010 float dy1 = delta1.dy * mPointerYZoomScale;
6011 float dx2 = delta2.dx * mPointerXZoomScale;
6012 float dy2 = delta2.dy * mPointerYZoomScale;
6013 float dot = dx1 * dx2 + dy1 * dy2;
6014 float cosine = dot / (dist1 * dist2); // denominator always > 0
6015 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6016 // Pointers are moving in the same direction. Switch to SWIPE.
6017#if DEBUG_GESTURES
6018 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6019 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6020 "cosine %0.3f >= %0.3f",
6021 dist1, mConfig.pointerGestureMultitouchMinDistance,
6022 dist2, mConfig.pointerGestureMultitouchMinDistance,
6023 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6024#endif
6025 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6026 } else {
6027 // Pointers are moving in different directions. Switch to FREEFORM.
6028#if DEBUG_GESTURES
6029 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6030 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6031 "cosine %0.3f < %0.3f",
6032 dist1, mConfig.pointerGestureMultitouchMinDistance,
6033 dist2, mConfig.pointerGestureMultitouchMinDistance,
6034 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6035#endif
6036 *outCancelPreviousGesture = true;
6037 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6038 }
6039 }
6040 }
6041 }
6042 }
6043 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6044 // Switch from SWIPE to FREEFORM if additional pointers go down.
6045 // Cancel previous gesture.
6046 if (currentFingerCount > 2) {
6047#if DEBUG_GESTURES
6048 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6049 currentFingerCount);
6050#endif
6051 *outCancelPreviousGesture = true;
6052 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6053 }
6054 }
6055
6056 // Move the reference points based on the overall group motion of the fingers
6057 // except in PRESS mode while waiting for a transition to occur.
6058 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6059 && (commonDeltaX || commonDeltaY)) {
6060 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6061 uint32_t id = idBits.clearFirstMarkedBit();
6062 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6063 delta.dx = 0;
6064 delta.dy = 0;
6065 }
6066
6067 mPointerGesture.referenceTouchX += commonDeltaX;
6068 mPointerGesture.referenceTouchY += commonDeltaY;
6069
6070 commonDeltaX *= mPointerXMovementScale;
6071 commonDeltaY *= mPointerYMovementScale;
6072
6073 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6074 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6075
6076 mPointerGesture.referenceGestureX += commonDeltaX;
6077 mPointerGesture.referenceGestureY += commonDeltaY;
6078 }
6079
6080 // Report gestures.
6081 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6082 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6083 // PRESS or SWIPE mode.
6084#if DEBUG_GESTURES
6085 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6086 "activeGestureId=%d, currentTouchPointerCount=%d",
6087 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6088#endif
6089 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6090
6091 mPointerGesture.currentGestureIdBits.clear();
6092 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6093 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6094 mPointerGesture.currentGestureProperties[0].clear();
6095 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6096 mPointerGesture.currentGestureProperties[0].toolType =
6097 AMOTION_EVENT_TOOL_TYPE_FINGER;
6098 mPointerGesture.currentGestureCoords[0].clear();
6099 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6100 mPointerGesture.referenceGestureX);
6101 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6102 mPointerGesture.referenceGestureY);
6103 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6104 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6105 // FREEFORM mode.
6106#if DEBUG_GESTURES
6107 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6108 "activeGestureId=%d, currentTouchPointerCount=%d",
6109 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6110#endif
6111 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6112
6113 mPointerGesture.currentGestureIdBits.clear();
6114
6115 BitSet32 mappedTouchIdBits;
6116 BitSet32 usedGestureIdBits;
6117 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6118 // Initially, assign the active gesture id to the active touch point
6119 // if there is one. No other touch id bits are mapped yet.
6120 if (!*outCancelPreviousGesture) {
6121 mappedTouchIdBits.markBit(activeTouchId);
6122 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6123 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6124 mPointerGesture.activeGestureId;
6125 } else {
6126 mPointerGesture.activeGestureId = -1;
6127 }
6128 } else {
6129 // Otherwise, assume we mapped all touches from the previous frame.
6130 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006131 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6132 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006133 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6134
6135 // Check whether we need to choose a new active gesture id because the
6136 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006137 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6138 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006139 !upTouchIdBits.isEmpty(); ) {
6140 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6141 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6142 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6143 mPointerGesture.activeGestureId = -1;
6144 break;
6145 }
6146 }
6147 }
6148
6149#if DEBUG_GESTURES
6150 ALOGD("Gestures: FREEFORM follow up "
6151 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6152 "activeGestureId=%d",
6153 mappedTouchIdBits.value, usedGestureIdBits.value,
6154 mPointerGesture.activeGestureId);
6155#endif
6156
Michael Wright842500e2015-03-13 17:32:02 -07006157 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006158 for (uint32_t i = 0; i < currentFingerCount; i++) {
6159 uint32_t touchId = idBits.clearFirstMarkedBit();
6160 uint32_t gestureId;
6161 if (!mappedTouchIdBits.hasBit(touchId)) {
6162 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6163 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6164#if DEBUG_GESTURES
6165 ALOGD("Gestures: FREEFORM "
6166 "new mapping for touch id %d -> gesture id %d",
6167 touchId, gestureId);
6168#endif
6169 } else {
6170 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6171#if DEBUG_GESTURES
6172 ALOGD("Gestures: FREEFORM "
6173 "existing mapping for touch id %d -> gesture id %d",
6174 touchId, gestureId);
6175#endif
6176 }
6177 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6178 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6179
6180 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006181 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006182 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6183 * mPointerXZoomScale;
6184 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6185 * mPointerYZoomScale;
6186 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6187
6188 mPointerGesture.currentGestureProperties[i].clear();
6189 mPointerGesture.currentGestureProperties[i].id = gestureId;
6190 mPointerGesture.currentGestureProperties[i].toolType =
6191 AMOTION_EVENT_TOOL_TYPE_FINGER;
6192 mPointerGesture.currentGestureCoords[i].clear();
6193 mPointerGesture.currentGestureCoords[i].setAxisValue(
6194 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6195 mPointerGesture.currentGestureCoords[i].setAxisValue(
6196 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6197 mPointerGesture.currentGestureCoords[i].setAxisValue(
6198 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6199 }
6200
6201 if (mPointerGesture.activeGestureId < 0) {
6202 mPointerGesture.activeGestureId =
6203 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6204#if DEBUG_GESTURES
6205 ALOGD("Gestures: FREEFORM new "
6206 "activeGestureId=%d", mPointerGesture.activeGestureId);
6207#endif
6208 }
6209 }
6210 }
6211
Michael Wright842500e2015-03-13 17:32:02 -07006212 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213
6214#if DEBUG_GESTURES
6215 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6216 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6217 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6218 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6219 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6220 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6221 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6222 uint32_t id = idBits.clearFirstMarkedBit();
6223 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6224 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6225 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6226 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6227 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6228 id, index, properties.toolType,
6229 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6230 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6231 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6232 }
6233 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6234 uint32_t id = idBits.clearFirstMarkedBit();
6235 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6236 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6237 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6238 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6239 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6240 id, index, properties.toolType,
6241 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6242 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6243 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6244 }
6245#endif
6246 return true;
6247}
6248
6249void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6250 mPointerSimple.currentCoords.clear();
6251 mPointerSimple.currentProperties.clear();
6252
6253 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006254 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6255 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6256 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6257 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6258 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006259 mPointerController->setPosition(x, y);
6260
Michael Wright842500e2015-03-13 17:32:02 -07006261 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262 down = !hovering;
6263
6264 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006265 mPointerSimple.currentCoords.copyFrom(
6266 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6268 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6269 mPointerSimple.currentProperties.id = 0;
6270 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006271 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272 } else {
6273 down = false;
6274 hovering = false;
6275 }
6276
6277 dispatchPointerSimple(when, policyFlags, down, hovering);
6278}
6279
6280void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6281 abortPointerSimple(when, policyFlags);
6282}
6283
6284void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6285 mPointerSimple.currentCoords.clear();
6286 mPointerSimple.currentProperties.clear();
6287
6288 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006289 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6290 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6291 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006292 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006293 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6294 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006295 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006296 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006297 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006298 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006299 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006300 * mPointerYMovementScale;
6301
6302 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6303 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6304
6305 mPointerController->move(deltaX, deltaY);
6306 } else {
6307 mPointerVelocityControl.reset();
6308 }
6309
Michael Wright842500e2015-03-13 17:32:02 -07006310 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311 hovering = !down;
6312
6313 float x, y;
6314 mPointerController->getPosition(&x, &y);
6315 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006316 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6318 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6319 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6320 hovering ? 0.0f : 1.0f);
6321 mPointerSimple.currentProperties.id = 0;
6322 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006323 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006324 } else {
6325 mPointerVelocityControl.reset();
6326
6327 down = false;
6328 hovering = false;
6329 }
6330
6331 dispatchPointerSimple(when, policyFlags, down, hovering);
6332}
6333
6334void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6335 abortPointerSimple(when, policyFlags);
6336
6337 mPointerVelocityControl.reset();
6338}
6339
6340void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6341 bool down, bool hovering) {
6342 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006343 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344
Yi Kong9b14ac62018-07-17 13:48:38 -07006345 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346 if (down || hovering) {
6347 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6348 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006349 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006350 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6351 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6352 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6353 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006354 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006355 }
6356
6357 if (mPointerSimple.down && !down) {
6358 mPointerSimple.down = false;
6359
6360 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006361 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006362 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006363 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6364 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006365 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6366 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006367 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 getListener()->notifyMotion(&args);
6369 }
6370
6371 if (mPointerSimple.hovering && !hovering) {
6372 mPointerSimple.hovering = false;
6373
6374 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006375 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6376 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006377 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6378 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6380 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006381 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006382 getListener()->notifyMotion(&args);
6383 }
6384
6385 if (down) {
6386 if (!mPointerSimple.down) {
6387 mPointerSimple.down = true;
6388 mPointerSimple.downTime = when;
6389
6390 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006391 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6392 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006393 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6394 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006395 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006396 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6397 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006398 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006399 getListener()->notifyMotion(&args);
6400 }
6401
6402 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006403 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6404 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006405 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6406 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6408 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006409 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006410 getListener()->notifyMotion(&args);
6411 }
6412
6413 if (hovering) {
6414 if (!mPointerSimple.hovering) {
6415 mPointerSimple.hovering = true;
6416
6417 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006418 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6419 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006420 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006421 mCurrentRawState.buttonState, MotionClassification::NONE,
6422 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6424 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006425 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426 getListener()->notifyMotion(&args);
6427 }
6428
6429 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006430 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6431 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006432 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006433 mCurrentRawState.buttonState, MotionClassification::NONE,
6434 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006435 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6436 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006437 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 getListener()->notifyMotion(&args);
6439 }
6440
Michael Wright842500e2015-03-13 17:32:02 -07006441 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6442 float vscroll = mCurrentRawState.rawVScroll;
6443 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006444 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6445 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446
6447 // Send scroll.
6448 PointerCoords pointerCoords;
6449 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6450 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6451 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6452
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006453 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6454 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006455 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6456 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006457 1, &mPointerSimple.currentProperties, &pointerCoords,
6458 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006459 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006460 getListener()->notifyMotion(&args);
6461 }
6462
6463 // Save state.
6464 if (down || hovering) {
6465 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6466 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6467 } else {
6468 mPointerSimple.reset();
6469 }
6470}
6471
6472void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6473 mPointerSimple.currentCoords.clear();
6474 mPointerSimple.currentProperties.clear();
6475
6476 dispatchPointerSimple(when, policyFlags, false, false);
6477}
6478
6479void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006480 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006481 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006482 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006483 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6484 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006485 PointerCoords pointerCoords[MAX_POINTERS];
6486 PointerProperties pointerProperties[MAX_POINTERS];
6487 uint32_t pointerCount = 0;
6488 while (!idBits.isEmpty()) {
6489 uint32_t id = idBits.clearFirstMarkedBit();
6490 uint32_t index = idToIndex[id];
6491 pointerProperties[pointerCount].copyFrom(properties[index]);
6492 pointerCoords[pointerCount].copyFrom(coords[index]);
6493
6494 if (changedId >= 0 && id == uint32_t(changedId)) {
6495 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6496 }
6497
6498 pointerCount += 1;
6499 }
6500
6501 ALOG_ASSERT(pointerCount != 0);
6502
6503 if (changedId >= 0 && pointerCount == 1) {
6504 // Replace initial down and final up action.
6505 // We can compare the action without masking off the changed pointer index
6506 // because we know the index is 0.
6507 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6508 action = AMOTION_EVENT_ACTION_DOWN;
6509 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6510 action = AMOTION_EVENT_ACTION_UP;
6511 } else {
6512 // Can't happen.
6513 ALOG_ASSERT(false);
6514 }
6515 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006516 const int32_t displayId = mPointerController != nullptr ?
6517 mPointerController->getDisplayId() : mViewport.displayId;
Dan Harmsaca28402018-12-17 13:55:20 -08006518
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006519 const int32_t deviceId = getDeviceId();
6520 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6521 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006522 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006523 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6524 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006525 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526 getListener()->notifyMotion(&args);
6527}
6528
6529bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6530 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6531 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6532 BitSet32 idBits) const {
6533 bool changed = false;
6534 while (!idBits.isEmpty()) {
6535 uint32_t id = idBits.clearFirstMarkedBit();
6536 uint32_t inIndex = inIdToIndex[id];
6537 uint32_t outIndex = outIdToIndex[id];
6538
6539 const PointerProperties& curInProperties = inProperties[inIndex];
6540 const PointerCoords& curInCoords = inCoords[inIndex];
6541 PointerProperties& curOutProperties = outProperties[outIndex];
6542 PointerCoords& curOutCoords = outCoords[outIndex];
6543
6544 if (curInProperties != curOutProperties) {
6545 curOutProperties.copyFrom(curInProperties);
6546 changed = true;
6547 }
6548
6549 if (curInCoords != curOutCoords) {
6550 curOutCoords.copyFrom(curInCoords);
6551 changed = true;
6552 }
6553 }
6554 return changed;
6555}
6556
6557void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006558 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006559 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6560 }
6561}
6562
Jeff Brownc9aa6282015-02-11 19:03:28 -08006563void TouchInputMapper::cancelTouch(nsecs_t when) {
6564 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006565 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006566}
6567
Michael Wrightd02c5b62014-02-10 15:10:22 -08006568bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006569 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006570 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006571 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006572 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6573 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6574 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006575}
6576
6577const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6578 int32_t x, int32_t y) {
6579 size_t numVirtualKeys = mVirtualKeys.size();
6580 for (size_t i = 0; i < numVirtualKeys; i++) {
6581 const VirtualKey& virtualKey = mVirtualKeys[i];
6582
6583#if DEBUG_VIRTUAL_KEYS
6584 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6585 "left=%d, top=%d, right=%d, bottom=%d",
6586 x, y,
6587 virtualKey.keyCode, virtualKey.scanCode,
6588 virtualKey.hitLeft, virtualKey.hitTop,
6589 virtualKey.hitRight, virtualKey.hitBottom);
6590#endif
6591
6592 if (virtualKey.isHit(x, y)) {
6593 return & virtualKey;
6594 }
6595 }
6596
Yi Kong9b14ac62018-07-17 13:48:38 -07006597 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006598}
6599
Michael Wright842500e2015-03-13 17:32:02 -07006600void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6601 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6602 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006603
Michael Wright842500e2015-03-13 17:32:02 -07006604 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006605
6606 if (currentPointerCount == 0) {
6607 // No pointers to assign.
6608 return;
6609 }
6610
6611 if (lastPointerCount == 0) {
6612 // All pointers are new.
6613 for (uint32_t i = 0; i < currentPointerCount; i++) {
6614 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006615 current->rawPointerData.pointers[i].id = id;
6616 current->rawPointerData.idToIndex[id] = i;
6617 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006618 }
6619 return;
6620 }
6621
6622 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006623 && current->rawPointerData.pointers[0].toolType
6624 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006625 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006626 uint32_t id = last->rawPointerData.pointers[0].id;
6627 current->rawPointerData.pointers[0].id = id;
6628 current->rawPointerData.idToIndex[id] = 0;
6629 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 return;
6631 }
6632
6633 // General case.
6634 // We build a heap of squared euclidean distances between current and last pointers
6635 // associated with the current and last pointer indices. Then, we find the best
6636 // match (by distance) for each current pointer.
6637 // The pointers must have the same tool type but it is possible for them to
6638 // transition from hovering to touching or vice-versa while retaining the same id.
6639 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6640
6641 uint32_t heapSize = 0;
6642 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6643 currentPointerIndex++) {
6644 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6645 lastPointerIndex++) {
6646 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006647 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006648 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006649 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006650 if (currentPointer.toolType == lastPointer.toolType) {
6651 int64_t deltaX = currentPointer.x - lastPointer.x;
6652 int64_t deltaY = currentPointer.y - lastPointer.y;
6653
6654 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6655
6656 // Insert new element into the heap (sift up).
6657 heap[heapSize].currentPointerIndex = currentPointerIndex;
6658 heap[heapSize].lastPointerIndex = lastPointerIndex;
6659 heap[heapSize].distance = distance;
6660 heapSize += 1;
6661 }
6662 }
6663 }
6664
6665 // Heapify
6666 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6667 startIndex -= 1;
6668 for (uint32_t parentIndex = startIndex; ;) {
6669 uint32_t childIndex = parentIndex * 2 + 1;
6670 if (childIndex >= heapSize) {
6671 break;
6672 }
6673
6674 if (childIndex + 1 < heapSize
6675 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6676 childIndex += 1;
6677 }
6678
6679 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6680 break;
6681 }
6682
6683 swap(heap[parentIndex], heap[childIndex]);
6684 parentIndex = childIndex;
6685 }
6686 }
6687
6688#if DEBUG_POINTER_ASSIGNMENT
6689 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6690 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006691 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006692 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6693 heap[i].distance);
6694 }
6695#endif
6696
6697 // Pull matches out by increasing order of distance.
6698 // To avoid reassigning pointers that have already been matched, the loop keeps track
6699 // of which last and current pointers have been matched using the matchedXXXBits variables.
6700 // It also tracks the used pointer id bits.
6701 BitSet32 matchedLastBits(0);
6702 BitSet32 matchedCurrentBits(0);
6703 BitSet32 usedIdBits(0);
6704 bool first = true;
6705 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6706 while (heapSize > 0) {
6707 if (first) {
6708 // The first time through the loop, we just consume the root element of
6709 // the heap (the one with smallest distance).
6710 first = false;
6711 } else {
6712 // Previous iterations consumed the root element of the heap.
6713 // Pop root element off of the heap (sift down).
6714 heap[0] = heap[heapSize];
6715 for (uint32_t parentIndex = 0; ;) {
6716 uint32_t childIndex = parentIndex * 2 + 1;
6717 if (childIndex >= heapSize) {
6718 break;
6719 }
6720
6721 if (childIndex + 1 < heapSize
6722 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6723 childIndex += 1;
6724 }
6725
6726 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6727 break;
6728 }
6729
6730 swap(heap[parentIndex], heap[childIndex]);
6731 parentIndex = childIndex;
6732 }
6733
6734#if DEBUG_POINTER_ASSIGNMENT
6735 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6736 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006737 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006738 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6739 heap[i].distance);
6740 }
6741#endif
6742 }
6743
6744 heapSize -= 1;
6745
6746 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6747 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6748
6749 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6750 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6751
6752 matchedCurrentBits.markBit(currentPointerIndex);
6753 matchedLastBits.markBit(lastPointerIndex);
6754
Michael Wright842500e2015-03-13 17:32:02 -07006755 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6756 current->rawPointerData.pointers[currentPointerIndex].id = id;
6757 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6758 current->rawPointerData.markIdBit(id,
6759 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006760 usedIdBits.markBit(id);
6761
6762#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006763 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6764 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006765 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6766#endif
6767 break;
6768 }
6769 }
6770
6771 // Assign fresh ids to pointers that were not matched in the process.
6772 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6773 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6774 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6775
Michael Wright842500e2015-03-13 17:32:02 -07006776 current->rawPointerData.pointers[currentPointerIndex].id = id;
6777 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6778 current->rawPointerData.markIdBit(id,
6779 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006780
6781#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006782 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006783#endif
6784 }
6785}
6786
6787int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6788 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6789 return AKEY_STATE_VIRTUAL;
6790 }
6791
6792 size_t numVirtualKeys = mVirtualKeys.size();
6793 for (size_t i = 0; i < numVirtualKeys; i++) {
6794 const VirtualKey& virtualKey = mVirtualKeys[i];
6795 if (virtualKey.keyCode == keyCode) {
6796 return AKEY_STATE_UP;
6797 }
6798 }
6799
6800 return AKEY_STATE_UNKNOWN;
6801}
6802
6803int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6804 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6805 return AKEY_STATE_VIRTUAL;
6806 }
6807
6808 size_t numVirtualKeys = mVirtualKeys.size();
6809 for (size_t i = 0; i < numVirtualKeys; i++) {
6810 const VirtualKey& virtualKey = mVirtualKeys[i];
6811 if (virtualKey.scanCode == scanCode) {
6812 return AKEY_STATE_UP;
6813 }
6814 }
6815
6816 return AKEY_STATE_UNKNOWN;
6817}
6818
6819bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6820 const int32_t* keyCodes, uint8_t* outFlags) {
6821 size_t numVirtualKeys = mVirtualKeys.size();
6822 for (size_t i = 0; i < numVirtualKeys; i++) {
6823 const VirtualKey& virtualKey = mVirtualKeys[i];
6824
6825 for (size_t i = 0; i < numCodes; i++) {
6826 if (virtualKey.keyCode == keyCodes[i]) {
6827 outFlags[i] = 1;
6828 }
6829 }
6830 }
6831
6832 return true;
6833}
6834
6835
6836// --- SingleTouchInputMapper ---
6837
6838SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6839 TouchInputMapper(device) {
6840}
6841
6842SingleTouchInputMapper::~SingleTouchInputMapper() {
6843}
6844
6845void SingleTouchInputMapper::reset(nsecs_t when) {
6846 mSingleTouchMotionAccumulator.reset(getDevice());
6847
6848 TouchInputMapper::reset(when);
6849}
6850
6851void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6852 TouchInputMapper::process(rawEvent);
6853
6854 mSingleTouchMotionAccumulator.process(rawEvent);
6855}
6856
Michael Wright842500e2015-03-13 17:32:02 -07006857void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006858 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006859 outState->rawPointerData.pointerCount = 1;
6860 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006861
6862 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6863 && (mTouchButtonAccumulator.isHovering()
6864 || (mRawPointerAxes.pressure.valid
6865 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006866 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006867
Michael Wright842500e2015-03-13 17:32:02 -07006868 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006869 outPointer.id = 0;
6870 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6871 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6872 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6873 outPointer.touchMajor = 0;
6874 outPointer.touchMinor = 0;
6875 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6876 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6877 outPointer.orientation = 0;
6878 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6879 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6880 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6881 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6882 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6883 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6884 }
6885 outPointer.isHovering = isHovering;
6886 }
6887}
6888
6889void SingleTouchInputMapper::configureRawPointerAxes() {
6890 TouchInputMapper::configureRawPointerAxes();
6891
6892 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6893 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6894 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6895 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6896 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6897 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6898 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6899}
6900
6901bool SingleTouchInputMapper::hasStylus() const {
6902 return mTouchButtonAccumulator.hasStylus();
6903}
6904
6905
6906// --- MultiTouchInputMapper ---
6907
6908MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6909 TouchInputMapper(device) {
6910}
6911
6912MultiTouchInputMapper::~MultiTouchInputMapper() {
6913}
6914
6915void MultiTouchInputMapper::reset(nsecs_t when) {
6916 mMultiTouchMotionAccumulator.reset(getDevice());
6917
6918 mPointerIdBits.clear();
6919
6920 TouchInputMapper::reset(when);
6921}
6922
6923void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6924 TouchInputMapper::process(rawEvent);
6925
6926 mMultiTouchMotionAccumulator.process(rawEvent);
6927}
6928
Michael Wright842500e2015-03-13 17:32:02 -07006929void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006930 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6931 size_t outCount = 0;
6932 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006933 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006934
6935 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6936 const MultiTouchMotionAccumulator::Slot* inSlot =
6937 mMultiTouchMotionAccumulator.getSlot(inIndex);
6938 if (!inSlot->isInUse()) {
6939 continue;
6940 }
6941
6942 if (outCount >= MAX_POINTERS) {
6943#if DEBUG_POINTERS
6944 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6945 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006946 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947#endif
6948 break; // too many fingers!
6949 }
6950
Michael Wright842500e2015-03-13 17:32:02 -07006951 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006952 outPointer.x = inSlot->getX();
6953 outPointer.y = inSlot->getY();
6954 outPointer.pressure = inSlot->getPressure();
6955 outPointer.touchMajor = inSlot->getTouchMajor();
6956 outPointer.touchMinor = inSlot->getTouchMinor();
6957 outPointer.toolMajor = inSlot->getToolMajor();
6958 outPointer.toolMinor = inSlot->getToolMinor();
6959 outPointer.orientation = inSlot->getOrientation();
6960 outPointer.distance = inSlot->getDistance();
6961 outPointer.tiltX = 0;
6962 outPointer.tiltY = 0;
6963
6964 outPointer.toolType = inSlot->getToolType();
6965 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6966 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6967 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6968 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6969 }
6970 }
6971
6972 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6973 && (mTouchButtonAccumulator.isHovering()
6974 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6975 outPointer.isHovering = isHovering;
6976
6977 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006978 if (mHavePointerIds) {
6979 int32_t trackingId = inSlot->getTrackingId();
6980 int32_t id = -1;
6981 if (trackingId >= 0) {
6982 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6983 uint32_t n = idBits.clearFirstMarkedBit();
6984 if (mPointerTrackingIdMap[n] == trackingId) {
6985 id = n;
6986 }
6987 }
6988
6989 if (id < 0 && !mPointerIdBits.isFull()) {
6990 id = mPointerIdBits.markFirstUnmarkedBit();
6991 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006992 }
Michael Wright842500e2015-03-13 17:32:02 -07006993 }
gaoshang1a632de2016-08-24 10:23:50 +08006994 if (id < 0) {
6995 mHavePointerIds = false;
6996 outState->rawPointerData.clearIdBits();
6997 newPointerIdBits.clear();
6998 } else {
6999 outPointer.id = id;
7000 outState->rawPointerData.idToIndex[id] = outCount;
7001 outState->rawPointerData.markIdBit(id, isHovering);
7002 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007003 }
Michael Wright842500e2015-03-13 17:32:02 -07007004 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007005 outCount += 1;
7006 }
7007
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007008 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07007009 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007010 mPointerIdBits = newPointerIdBits;
7011
7012 mMultiTouchMotionAccumulator.finishSync();
7013}
7014
7015void MultiTouchInputMapper::configureRawPointerAxes() {
7016 TouchInputMapper::configureRawPointerAxes();
7017
7018 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7019 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7020 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7021 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7022 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7023 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7024 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7025 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7026 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7027 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7028 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7029
7030 if (mRawPointerAxes.trackingId.valid
7031 && mRawPointerAxes.slot.valid
7032 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7033 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7034 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007035 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7036 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007037 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007038 slotCount = MAX_SLOTS;
7039 }
7040 mMultiTouchMotionAccumulator.configure(getDevice(),
7041 slotCount, true /*usingSlotsProtocol*/);
7042 } else {
7043 mMultiTouchMotionAccumulator.configure(getDevice(),
7044 MAX_POINTERS, false /*usingSlotsProtocol*/);
7045 }
7046}
7047
7048bool MultiTouchInputMapper::hasStylus() const {
7049 return mMultiTouchMotionAccumulator.hasStylus()
7050 || mTouchButtonAccumulator.hasStylus();
7051}
7052
Michael Wright842500e2015-03-13 17:32:02 -07007053// --- ExternalStylusInputMapper
7054
7055ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7056 InputMapper(device) {
7057
7058}
7059
7060uint32_t ExternalStylusInputMapper::getSources() {
7061 return AINPUT_SOURCE_STYLUS;
7062}
7063
7064void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7065 InputMapper::populateDeviceInfo(info);
7066 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7067 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7068}
7069
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007070void ExternalStylusInputMapper::dump(std::string& dump) {
7071 dump += INDENT2 "External Stylus Input Mapper:\n";
7072 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007073 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007074 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007075 dumpStylusState(dump, mStylusState);
7076}
7077
7078void ExternalStylusInputMapper::configure(nsecs_t when,
7079 const InputReaderConfiguration* config, uint32_t changes) {
7080 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7081 mTouchButtonAccumulator.configure(getDevice());
7082}
7083
7084void ExternalStylusInputMapper::reset(nsecs_t when) {
7085 InputDevice* device = getDevice();
7086 mSingleTouchMotionAccumulator.reset(device);
7087 mTouchButtonAccumulator.reset(device);
7088 InputMapper::reset(when);
7089}
7090
7091void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7092 mSingleTouchMotionAccumulator.process(rawEvent);
7093 mTouchButtonAccumulator.process(rawEvent);
7094
7095 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7096 sync(rawEvent->when);
7097 }
7098}
7099
7100void ExternalStylusInputMapper::sync(nsecs_t when) {
7101 mStylusState.clear();
7102
7103 mStylusState.when = when;
7104
Michael Wright45ccacf2015-04-21 19:01:58 +01007105 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7106 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7107 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7108 }
7109
Michael Wright842500e2015-03-13 17:32:02 -07007110 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7111 if (mRawPressureAxis.valid) {
7112 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7113 } else if (mTouchButtonAccumulator.isToolActive()) {
7114 mStylusState.pressure = 1.0f;
7115 } else {
7116 mStylusState.pressure = 0.0f;
7117 }
7118
7119 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007120
7121 mContext->dispatchExternalStylusState(mStylusState);
7122}
7123
Michael Wrightd02c5b62014-02-10 15:10:22 -08007124
7125// --- JoystickInputMapper ---
7126
7127JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7128 InputMapper(device) {
7129}
7130
7131JoystickInputMapper::~JoystickInputMapper() {
7132}
7133
7134uint32_t JoystickInputMapper::getSources() {
7135 return AINPUT_SOURCE_JOYSTICK;
7136}
7137
7138void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7139 InputMapper::populateDeviceInfo(info);
7140
7141 for (size_t i = 0; i < mAxes.size(); i++) {
7142 const Axis& axis = mAxes.valueAt(i);
7143 addMotionRange(axis.axisInfo.axis, axis, info);
7144
7145 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7146 addMotionRange(axis.axisInfo.highAxis, axis, info);
7147
7148 }
7149 }
7150}
7151
7152void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7153 InputDeviceInfo* info) {
7154 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7155 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7156 /* In order to ease the transition for developers from using the old axes
7157 * to the newer, more semantically correct axes, we'll continue to register
7158 * the old axes as duplicates of their corresponding new ones. */
7159 int32_t compatAxis = getCompatAxis(axisId);
7160 if (compatAxis >= 0) {
7161 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7162 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7163 }
7164}
7165
7166/* A mapping from axes the joystick actually has to the axes that should be
7167 * artificially created for compatibility purposes.
7168 * Returns -1 if no compatibility axis is needed. */
7169int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7170 switch(axis) {
7171 case AMOTION_EVENT_AXIS_LTRIGGER:
7172 return AMOTION_EVENT_AXIS_BRAKE;
7173 case AMOTION_EVENT_AXIS_RTRIGGER:
7174 return AMOTION_EVENT_AXIS_GAS;
7175 }
7176 return -1;
7177}
7178
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007179void JoystickInputMapper::dump(std::string& dump) {
7180 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007181
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007182 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183 size_t numAxes = mAxes.size();
7184 for (size_t i = 0; i < numAxes; i++) {
7185 const Axis& axis = mAxes.valueAt(i);
7186 const char* label = getAxisLabel(axis.axisInfo.axis);
7187 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007188 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007189 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007190 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007191 }
7192 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7193 label = getAxisLabel(axis.axisInfo.highAxis);
7194 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007195 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007196 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007197 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007198 axis.axisInfo.splitValue);
7199 }
7200 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007201 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007202 }
7203
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007204 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 -08007205 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007206 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007207 "highScale=%0.5f, highOffset=%0.5f\n",
7208 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007209 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007210 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7211 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7212 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7213 }
7214}
7215
7216void JoystickInputMapper::configure(nsecs_t when,
7217 const InputReaderConfiguration* config, uint32_t changes) {
7218 InputMapper::configure(when, config, changes);
7219
7220 if (!changes) { // first time only
7221 // Collect all axes.
7222 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7223 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7224 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7225 continue; // axis must be claimed by a different device
7226 }
7227
7228 RawAbsoluteAxisInfo rawAxisInfo;
7229 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7230 if (rawAxisInfo.valid) {
7231 // Map axis.
7232 AxisInfo axisInfo;
7233 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7234 if (!explicitlyMapped) {
7235 // Axis is not explicitly mapped, will choose a generic axis later.
7236 axisInfo.mode = AxisInfo::MODE_NORMAL;
7237 axisInfo.axis = -1;
7238 }
7239
7240 // Apply flat override.
7241 int32_t rawFlat = axisInfo.flatOverride < 0
7242 ? rawAxisInfo.flat : axisInfo.flatOverride;
7243
7244 // Calculate scaling factors and limits.
7245 Axis axis;
7246 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7247 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7248 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7249 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7250 scale, 0.0f, highScale, 0.0f,
7251 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7252 rawAxisInfo.resolution * scale);
7253 } else if (isCenteredAxis(axisInfo.axis)) {
7254 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7255 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7256 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7257 scale, offset, scale, offset,
7258 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7259 rawAxisInfo.resolution * scale);
7260 } else {
7261 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7262 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7263 scale, 0.0f, scale, 0.0f,
7264 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7265 rawAxisInfo.resolution * scale);
7266 }
7267
7268 // To eliminate noise while the joystick is at rest, filter out small variations
7269 // in axis values up front.
7270 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7271
7272 mAxes.add(abs, axis);
7273 }
7274 }
7275
7276 // If there are too many axes, start dropping them.
7277 // Prefer to keep explicitly mapped axes.
7278 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007279 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007280 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007281 pruneAxes(true);
7282 pruneAxes(false);
7283 }
7284
7285 // Assign generic axis ids to remaining axes.
7286 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7287 size_t numAxes = mAxes.size();
7288 for (size_t i = 0; i < numAxes; i++) {
7289 Axis& axis = mAxes.editValueAt(i);
7290 if (axis.axisInfo.axis < 0) {
7291 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7292 && haveAxis(nextGenericAxisId)) {
7293 nextGenericAxisId += 1;
7294 }
7295
7296 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7297 axis.axisInfo.axis = nextGenericAxisId;
7298 nextGenericAxisId += 1;
7299 } else {
7300 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7301 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007302 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007303 mAxes.removeItemsAt(i--);
7304 numAxes -= 1;
7305 }
7306 }
7307 }
7308 }
7309}
7310
7311bool JoystickInputMapper::haveAxis(int32_t axisId) {
7312 size_t numAxes = mAxes.size();
7313 for (size_t i = 0; i < numAxes; i++) {
7314 const Axis& axis = mAxes.valueAt(i);
7315 if (axis.axisInfo.axis == axisId
7316 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7317 && axis.axisInfo.highAxis == axisId)) {
7318 return true;
7319 }
7320 }
7321 return false;
7322}
7323
7324void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7325 size_t i = mAxes.size();
7326 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7327 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7328 continue;
7329 }
7330 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007331 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007332 mAxes.removeItemsAt(i);
7333 }
7334}
7335
7336bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7337 switch (axis) {
7338 case AMOTION_EVENT_AXIS_X:
7339 case AMOTION_EVENT_AXIS_Y:
7340 case AMOTION_EVENT_AXIS_Z:
7341 case AMOTION_EVENT_AXIS_RX:
7342 case AMOTION_EVENT_AXIS_RY:
7343 case AMOTION_EVENT_AXIS_RZ:
7344 case AMOTION_EVENT_AXIS_HAT_X:
7345 case AMOTION_EVENT_AXIS_HAT_Y:
7346 case AMOTION_EVENT_AXIS_ORIENTATION:
7347 case AMOTION_EVENT_AXIS_RUDDER:
7348 case AMOTION_EVENT_AXIS_WHEEL:
7349 return true;
7350 default:
7351 return false;
7352 }
7353}
7354
7355void JoystickInputMapper::reset(nsecs_t when) {
7356 // Recenter all axes.
7357 size_t numAxes = mAxes.size();
7358 for (size_t i = 0; i < numAxes; i++) {
7359 Axis& axis = mAxes.editValueAt(i);
7360 axis.resetValue();
7361 }
7362
7363 InputMapper::reset(when);
7364}
7365
7366void JoystickInputMapper::process(const RawEvent* rawEvent) {
7367 switch (rawEvent->type) {
7368 case EV_ABS: {
7369 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7370 if (index >= 0) {
7371 Axis& axis = mAxes.editValueAt(index);
7372 float newValue, highNewValue;
7373 switch (axis.axisInfo.mode) {
7374 case AxisInfo::MODE_INVERT:
7375 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7376 * axis.scale + axis.offset;
7377 highNewValue = 0.0f;
7378 break;
7379 case AxisInfo::MODE_SPLIT:
7380 if (rawEvent->value < axis.axisInfo.splitValue) {
7381 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7382 * axis.scale + axis.offset;
7383 highNewValue = 0.0f;
7384 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7385 newValue = 0.0f;
7386 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7387 * axis.highScale + axis.highOffset;
7388 } else {
7389 newValue = 0.0f;
7390 highNewValue = 0.0f;
7391 }
7392 break;
7393 default:
7394 newValue = rawEvent->value * axis.scale + axis.offset;
7395 highNewValue = 0.0f;
7396 break;
7397 }
7398 axis.newValue = newValue;
7399 axis.highNewValue = highNewValue;
7400 }
7401 break;
7402 }
7403
7404 case EV_SYN:
7405 switch (rawEvent->code) {
7406 case SYN_REPORT:
7407 sync(rawEvent->when, false /*force*/);
7408 break;
7409 }
7410 break;
7411 }
7412}
7413
7414void JoystickInputMapper::sync(nsecs_t when, bool force) {
7415 if (!filterAxes(force)) {
7416 return;
7417 }
7418
7419 int32_t metaState = mContext->getGlobalMetaState();
7420 int32_t buttonState = 0;
7421
7422 PointerProperties pointerProperties;
7423 pointerProperties.clear();
7424 pointerProperties.id = 0;
7425 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7426
7427 PointerCoords pointerCoords;
7428 pointerCoords.clear();
7429
7430 size_t numAxes = mAxes.size();
7431 for (size_t i = 0; i < numAxes; i++) {
7432 const Axis& axis = mAxes.valueAt(i);
7433 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7434 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7435 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7436 axis.highCurrentValue);
7437 }
7438 }
7439
7440 // Moving a joystick axis should not wake the device because joysticks can
7441 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7442 // button will likely wake the device.
7443 // TODO: Use the input device configuration to control this behavior more finely.
7444 uint32_t policyFlags = 0;
7445
Prabir Pradhan42611e02018-11-27 14:04:02 -08007446 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7447 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007448 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7449 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7450 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007451 getListener()->notifyMotion(&args);
7452}
7453
7454void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7455 int32_t axis, float value) {
7456 pointerCoords->setAxisValue(axis, value);
7457 /* In order to ease the transition for developers from using the old axes
7458 * to the newer, more semantically correct axes, we'll continue to produce
7459 * values for the old axes as mirrors of the value of their corresponding
7460 * new axes. */
7461 int32_t compatAxis = getCompatAxis(axis);
7462 if (compatAxis >= 0) {
7463 pointerCoords->setAxisValue(compatAxis, value);
7464 }
7465}
7466
7467bool JoystickInputMapper::filterAxes(bool force) {
7468 bool atLeastOneSignificantChange = force;
7469 size_t numAxes = mAxes.size();
7470 for (size_t i = 0; i < numAxes; i++) {
7471 Axis& axis = mAxes.editValueAt(i);
7472 if (force || hasValueChangedSignificantly(axis.filter,
7473 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7474 axis.currentValue = axis.newValue;
7475 atLeastOneSignificantChange = true;
7476 }
7477 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7478 if (force || hasValueChangedSignificantly(axis.filter,
7479 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7480 axis.highCurrentValue = axis.highNewValue;
7481 atLeastOneSignificantChange = true;
7482 }
7483 }
7484 }
7485 return atLeastOneSignificantChange;
7486}
7487
7488bool JoystickInputMapper::hasValueChangedSignificantly(
7489 float filter, float newValue, float currentValue, float min, float max) {
7490 if (newValue != currentValue) {
7491 // Filter out small changes in value unless the value is converging on the axis
7492 // bounds or center point. This is intended to reduce the amount of information
7493 // sent to applications by particularly noisy joysticks (such as PS3).
7494 if (fabs(newValue - currentValue) > filter
7495 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7496 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7497 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7498 return true;
7499 }
7500 }
7501 return false;
7502}
7503
7504bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7505 float filter, float newValue, float currentValue, float thresholdValue) {
7506 float newDistance = fabs(newValue - thresholdValue);
7507 if (newDistance < filter) {
7508 float oldDistance = fabs(currentValue - thresholdValue);
7509 if (newDistance < oldDistance) {
7510 return true;
7511 }
7512 }
7513 return false;
7514}
7515
7516} // namespace android