blob: 3e236a93ae7fd2e5426b14fb040dcd55602b5c64 [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
Siarhei Vishniakou3bc7e092019-07-24 17:43:30 -0700263InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
264 const sp<InputReaderPolicyInterface>& policy,
265 const sp<InputListenerInterface>& listener)
266 : mContext(this),
267 mEventHub(eventHub),
268 mPolicy(policy),
269 mNextSequenceNum(1),
270 mGlobalMetaState(0),
271 mGeneration(1),
272 mDisableVirtualKeysTimeout(LLONG_MIN),
273 mNextTimeout(LLONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800274 mConfigurationChangesToRefresh(0) {
275 mQueuedListener = new QueuedInputListener(listener);
276
277 { // acquire lock
278 AutoMutex _l(mLock);
279
280 refreshConfigurationLocked(0);
281 updateGlobalMetaStateLocked();
282 } // release lock
283}
284
285InputReader::~InputReader() {
286 for (size_t i = 0; i < mDevices.size(); i++) {
287 delete mDevices.valueAt(i);
288 }
289}
290
291void InputReader::loopOnce() {
292 int32_t oldGeneration;
293 int32_t timeoutMillis;
294 bool inputDevicesChanged = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800295 std::vector<InputDeviceInfo> inputDevices;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800296 { // acquire lock
297 AutoMutex _l(mLock);
298
299 oldGeneration = mGeneration;
300 timeoutMillis = -1;
301
302 uint32_t changes = mConfigurationChangesToRefresh;
303 if (changes) {
304 mConfigurationChangesToRefresh = 0;
305 timeoutMillis = 0;
306 refreshConfigurationLocked(changes);
307 } else if (mNextTimeout != LLONG_MAX) {
308 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
309 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
310 }
311 } // release lock
312
313 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
314
315 { // acquire lock
316 AutoMutex _l(mLock);
317 mReaderIsAliveCondition.broadcast();
318
319 if (count) {
320 processEventsLocked(mEventBuffer, count);
321 }
322
323 if (mNextTimeout != LLONG_MAX) {
324 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
325 if (now >= mNextTimeout) {
326#if DEBUG_RAW_EVENTS
327 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
328#endif
329 mNextTimeout = LLONG_MAX;
330 timeoutExpiredLocked(now);
331 }
332 }
333
334 if (oldGeneration != mGeneration) {
335 inputDevicesChanged = true;
336 getInputDevicesLocked(inputDevices);
337 }
338 } // release lock
339
340 // Send out a message that the describes the changed input devices.
341 if (inputDevicesChanged) {
342 mPolicy->notifyInputDevicesChanged(inputDevices);
343 }
344
345 // Flush queued events out to the listener.
346 // This must happen outside of the lock because the listener could potentially call
347 // back into the InputReader's methods, such as getScanCodeState, or become blocked
348 // on another thread similarly waiting to acquire the InputReader lock thereby
349 // resulting in a deadlock. This situation is actually quite plausible because the
350 // listener is actually the input dispatcher, which calls into the window manager,
351 // which occasionally calls into the input reader.
352 mQueuedListener->flush();
353}
354
355void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
356 for (const RawEvent* rawEvent = rawEvents; count;) {
357 int32_t type = rawEvent->type;
358 size_t batchSize = 1;
359 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
360 int32_t deviceId = rawEvent->deviceId;
361 while (batchSize < count) {
362 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
363 || rawEvent[batchSize].deviceId != deviceId) {
364 break;
365 }
366 batchSize += 1;
367 }
368#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700369 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800370#endif
371 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
372 } else {
373 switch (rawEvent->type) {
374 case EventHubInterface::DEVICE_ADDED:
375 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
376 break;
377 case EventHubInterface::DEVICE_REMOVED:
378 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
379 break;
380 case EventHubInterface::FINISHED_DEVICE_SCAN:
381 handleConfigurationChangedLocked(rawEvent->when);
382 break;
383 default:
384 ALOG_ASSERT(false); // can't happen
385 break;
386 }
387 }
388 count -= batchSize;
389 rawEvent += batchSize;
390 }
391}
392
393void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
394 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
395 if (deviceIndex >= 0) {
396 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
397 return;
398 }
399
400 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
401 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
402 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
403
404 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
405 device->configure(when, &mConfig, 0);
406 device->reset(when);
407
408 if (device->isIgnored()) {
409 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100410 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800411 } else {
412 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100413 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414 }
415
416 mDevices.add(deviceId, device);
417 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700418
419 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
420 notifyExternalStylusPresenceChanged();
421 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800422}
423
424void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700425 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800426 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
427 if (deviceIndex < 0) {
428 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
429 return;
430 }
431
432 device = mDevices.valueAt(deviceIndex);
433 mDevices.removeItemsAt(deviceIndex, 1);
434 bumpGenerationLocked();
435
436 if (device->isIgnored()) {
437 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100438 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 } else {
440 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100441 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800442 }
443
Michael Wright842500e2015-03-13 17:32:02 -0700444 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
445 notifyExternalStylusPresenceChanged();
446 }
447
Michael Wrightd02c5b62014-02-10 15:10:22 -0800448 device->reset(when);
449 delete device;
450}
451
452InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
453 const InputDeviceIdentifier& identifier, uint32_t classes) {
454 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
455 controllerNumber, identifier, classes);
456
457 // External devices.
458 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
459 device->setExternal(true);
460 }
461
Tim Kilbourn063ff532015-04-08 10:26:18 -0700462 // Devices with mics.
463 if (classes & INPUT_DEVICE_CLASS_MIC) {
464 device->setMic(true);
465 }
466
Michael Wrightd02c5b62014-02-10 15:10:22 -0800467 // Switch-like devices.
468 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
469 device->addMapper(new SwitchInputMapper(device));
470 }
471
Prashant Malani1941ff52015-08-11 18:29:28 -0700472 // Scroll wheel-like devices.
473 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
474 device->addMapper(new RotaryEncoderInputMapper(device));
475 }
476
Michael Wrightd02c5b62014-02-10 15:10:22 -0800477 // Vibrator-like devices.
478 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
479 device->addMapper(new VibratorInputMapper(device));
480 }
481
482 // Keyboard-like devices.
483 uint32_t keyboardSource = 0;
484 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
485 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
486 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
487 }
488 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
489 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
490 }
491 if (classes & INPUT_DEVICE_CLASS_DPAD) {
492 keyboardSource |= AINPUT_SOURCE_DPAD;
493 }
494 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
495 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
496 }
497
498 if (keyboardSource != 0) {
499 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
500 }
501
502 // Cursor-like devices.
503 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
504 device->addMapper(new CursorInputMapper(device));
505 }
506
507 // Touchscreens and touchpad devices.
508 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
509 device->addMapper(new MultiTouchInputMapper(device));
510 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
511 device->addMapper(new SingleTouchInputMapper(device));
512 }
513
514 // Joystick-like devices.
515 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
516 device->addMapper(new JoystickInputMapper(device));
517 }
518
Michael Wright842500e2015-03-13 17:32:02 -0700519 // External stylus-like devices.
520 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
521 device->addMapper(new ExternalStylusInputMapper(device));
522 }
523
Michael Wrightd02c5b62014-02-10 15:10:22 -0800524 return device;
525}
526
527void InputReader::processEventsForDeviceLocked(int32_t deviceId,
528 const RawEvent* rawEvents, size_t count) {
529 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
530 if (deviceIndex < 0) {
531 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
532 return;
533 }
534
535 InputDevice* device = mDevices.valueAt(deviceIndex);
536 if (device->isIgnored()) {
537 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
538 return;
539 }
540
541 device->process(rawEvents, count);
542}
543
544void InputReader::timeoutExpiredLocked(nsecs_t when) {
545 for (size_t i = 0; i < mDevices.size(); i++) {
546 InputDevice* device = mDevices.valueAt(i);
547 if (!device->isIgnored()) {
548 device->timeoutExpired(when);
549 }
550 }
551}
552
553void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
554 // Reset global meta state because it depends on the list of all configured devices.
555 updateGlobalMetaStateLocked();
556
557 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800558 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800559 mQueuedListener->notifyConfigurationChanged(&args);
560}
561
562void InputReader::refreshConfigurationLocked(uint32_t changes) {
563 mPolicy->getReaderConfiguration(&mConfig);
564 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
565
566 if (changes) {
Siarhei Vishniakouc5ae0dc2019-07-10 15:51:18 -0700567 ALOGI("Reconfiguring input devices, changes=%s",
568 InputReaderConfiguration::changesToString(changes).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800569 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
570
571 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
572 mEventHub->requestReopenDevices();
573 } else {
574 for (size_t i = 0; i < mDevices.size(); i++) {
575 InputDevice* device = mDevices.valueAt(i);
576 device->configure(now, &mConfig, changes);
577 }
578 }
579 }
580}
581
582void InputReader::updateGlobalMetaStateLocked() {
583 mGlobalMetaState = 0;
584
585 for (size_t i = 0; i < mDevices.size(); i++) {
586 InputDevice* device = mDevices.valueAt(i);
587 mGlobalMetaState |= device->getMetaState();
588 }
589}
590
591int32_t InputReader::getGlobalMetaStateLocked() {
592 return mGlobalMetaState;
593}
594
Michael Wright842500e2015-03-13 17:32:02 -0700595void InputReader::notifyExternalStylusPresenceChanged() {
596 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
597}
598
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800599void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700600 for (size_t i = 0; i < mDevices.size(); i++) {
601 InputDevice* device = mDevices.valueAt(i);
602 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800603 InputDeviceInfo info;
604 device->getDeviceInfo(&info);
605 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700606 }
607 }
608}
609
610void InputReader::dispatchExternalStylusState(const StylusState& state) {
611 for (size_t i = 0; i < mDevices.size(); i++) {
612 InputDevice* device = mDevices.valueAt(i);
613 device->updateExternalStylusState(state);
614 }
615}
616
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
618 mDisableVirtualKeysTimeout = time;
619}
620
621bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
622 InputDevice* device, int32_t keyCode, int32_t scanCode) {
623 if (now < mDisableVirtualKeysTimeout) {
624 ALOGI("Dropping virtual key from device %s because virtual keys are "
625 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100626 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800627 (mDisableVirtualKeysTimeout - now) * 0.000001,
628 keyCode, scanCode);
629 return true;
630 } else {
631 return false;
632 }
633}
634
635void InputReader::fadePointerLocked() {
636 for (size_t i = 0; i < mDevices.size(); i++) {
637 InputDevice* device = mDevices.valueAt(i);
638 device->fadePointer();
639 }
640}
641
642void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
643 if (when < mNextTimeout) {
644 mNextTimeout = when;
645 mEventHub->wake();
646 }
647}
648
649int32_t InputReader::bumpGenerationLocked() {
650 return ++mGeneration;
651}
652
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800653void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800654 AutoMutex _l(mLock);
655 getInputDevicesLocked(outInputDevices);
656}
657
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800658void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800659 outInputDevices.clear();
660
661 size_t numDevices = mDevices.size();
662 for (size_t i = 0; i < numDevices; i++) {
663 InputDevice* device = mDevices.valueAt(i);
664 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800665 InputDeviceInfo info;
666 device->getDeviceInfo(&info);
667 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800668 }
669 }
670}
671
672int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
673 int32_t keyCode) {
674 AutoMutex _l(mLock);
675
676 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
677}
678
679int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
680 int32_t scanCode) {
681 AutoMutex _l(mLock);
682
683 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
684}
685
686int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
687 AutoMutex _l(mLock);
688
689 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
690}
691
692int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
693 GetStateFunc getStateFunc) {
694 int32_t result = AKEY_STATE_UNKNOWN;
695 if (deviceId >= 0) {
696 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
697 if (deviceIndex >= 0) {
698 InputDevice* device = mDevices.valueAt(deviceIndex);
699 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
700 result = (device->*getStateFunc)(sourceMask, code);
701 }
702 }
703 } else {
704 size_t numDevices = mDevices.size();
705 for (size_t i = 0; i < numDevices; i++) {
706 InputDevice* device = mDevices.valueAt(i);
707 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
708 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
709 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
710 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
711 if (currentResult >= AKEY_STATE_DOWN) {
712 return currentResult;
713 } else if (currentResult == AKEY_STATE_UP) {
714 result = currentResult;
715 }
716 }
717 }
718 }
719 return result;
720}
721
Andrii Kulian763a3a42016-03-08 10:46:16 -0800722void InputReader::toggleCapsLockState(int32_t deviceId) {
723 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
724 if (deviceIndex < 0) {
725 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
726 return;
727 }
728
729 InputDevice* device = mDevices.valueAt(deviceIndex);
730 if (device->isIgnored()) {
731 return;
732 }
733
734 device->updateMetaState(AKEYCODE_CAPS_LOCK);
735}
736
Michael Wrightd02c5b62014-02-10 15:10:22 -0800737bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
738 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
739 AutoMutex _l(mLock);
740
741 memset(outFlags, 0, numCodes);
742 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
743}
744
745bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
746 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
747 bool result = false;
748 if (deviceId >= 0) {
749 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
750 if (deviceIndex >= 0) {
751 InputDevice* device = mDevices.valueAt(deviceIndex);
752 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
753 result = device->markSupportedKeyCodes(sourceMask,
754 numCodes, keyCodes, outFlags);
755 }
756 }
757 } else {
758 size_t numDevices = mDevices.size();
759 for (size_t i = 0; i < numDevices; i++) {
760 InputDevice* device = mDevices.valueAt(i);
761 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
762 result |= device->markSupportedKeyCodes(sourceMask,
763 numCodes, keyCodes, outFlags);
764 }
765 }
766 }
767 return result;
768}
769
770void InputReader::requestRefreshConfiguration(uint32_t changes) {
771 AutoMutex _l(mLock);
772
773 if (changes) {
774 bool needWake = !mConfigurationChangesToRefresh;
775 mConfigurationChangesToRefresh |= changes;
776
777 if (needWake) {
778 mEventHub->wake();
779 }
780 }
781}
782
783void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
784 ssize_t repeat, int32_t token) {
785 AutoMutex _l(mLock);
786
787 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
788 if (deviceIndex >= 0) {
789 InputDevice* device = mDevices.valueAt(deviceIndex);
790 device->vibrate(pattern, patternSize, repeat, token);
791 }
792}
793
794void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
795 AutoMutex _l(mLock);
796
797 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
798 if (deviceIndex >= 0) {
799 InputDevice* device = mDevices.valueAt(deviceIndex);
800 device->cancelVibrate(token);
801 }
802}
803
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700804bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
805 AutoMutex _l(mLock);
806
807 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
808 if (deviceIndex >= 0) {
809 InputDevice* device = mDevices.valueAt(deviceIndex);
810 return device->isEnabled();
811 }
812 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
813 return false;
814}
815
Arthur Hungc23540e2018-11-29 20:42:11 +0800816bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
817 AutoMutex _l(mLock);
818
819 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
820 if (deviceIndex < 0) {
821 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
822 return false;
823 }
824
825 InputDevice* device = mDevices.valueAt(deviceIndex);
826 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplay();
827 // No associated display. By default, can dispatch to all displays.
828 if (!associatedDisplayId) {
829 return true;
830 }
831
832 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
833 ALOGW("Device has associated, but no associated display id.");
834 return true;
835 }
836
837 return *associatedDisplayId == displayId;
838}
839
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800840void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841 AutoMutex _l(mLock);
842
843 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800844 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847
848 for (size_t i = 0; i < mDevices.size(); i++) {
849 mDevices.valueAt(i)->dump(dump);
850 }
851
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += INDENT "Configuration:\n";
853 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
855 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100858 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800860 dump += "]\n";
861 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 mConfig.virtualKeyQuietTime * 0.000001f);
863
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800864 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
866 mConfig.pointerVelocityControlParameters.scale,
867 mConfig.pointerVelocityControlParameters.lowThreshold,
868 mConfig.pointerVelocityControlParameters.highThreshold,
869 mConfig.pointerVelocityControlParameters.acceleration);
870
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800871 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800872 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
873 mConfig.wheelVelocityControlParameters.scale,
874 mConfig.wheelVelocityControlParameters.lowThreshold,
875 mConfig.wheelVelocityControlParameters.highThreshold,
876 mConfig.wheelVelocityControlParameters.acceleration);
877
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800878 dump += StringPrintf(INDENT2 "PointerGesture:\n");
879 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800880 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800881 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800882 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800883 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800884 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800886 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800888 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800890 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800892 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800894 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800895 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800896 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800898 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800899 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800900 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800901 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800902 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700903
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800904 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700905 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800906}
907
908void InputReader::monitor() {
909 // Acquire and release the lock to ensure that the reader has not deadlocked.
910 mLock.lock();
911 mEventHub->wake();
912 mReaderIsAliveCondition.wait(mLock);
913 mLock.unlock();
914
915 // Check the EventHub
916 mEventHub->monitor();
917}
918
919
920// --- InputReader::ContextImpl ---
921
922InputReader::ContextImpl::ContextImpl(InputReader* reader) :
923 mReader(reader) {
924}
925
926void InputReader::ContextImpl::updateGlobalMetaState() {
927 // lock is already held by the input loop
928 mReader->updateGlobalMetaStateLocked();
929}
930
931int32_t InputReader::ContextImpl::getGlobalMetaState() {
932 // lock is already held by the input loop
933 return mReader->getGlobalMetaStateLocked();
934}
935
936void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
937 // lock is already held by the input loop
938 mReader->disableVirtualKeysUntilLocked(time);
939}
940
941bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
942 InputDevice* device, int32_t keyCode, int32_t scanCode) {
943 // lock is already held by the input loop
944 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
945}
946
947void InputReader::ContextImpl::fadePointer() {
948 // lock is already held by the input loop
949 mReader->fadePointerLocked();
950}
951
952void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
953 // lock is already held by the input loop
954 mReader->requestTimeoutAtTimeLocked(when);
955}
956
957int32_t InputReader::ContextImpl::bumpGeneration() {
958 // lock is already held by the input loop
959 return mReader->bumpGenerationLocked();
960}
961
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800962void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700963 // lock is already held by whatever called refreshConfigurationLocked
964 mReader->getExternalStylusDevicesLocked(outDevices);
965}
966
967void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
968 mReader->dispatchExternalStylusState(state);
969}
970
Michael Wrightd02c5b62014-02-10 15:10:22 -0800971InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
972 return mReader->mPolicy.get();
973}
974
975InputListenerInterface* InputReader::ContextImpl::getListener() {
976 return mReader->mQueuedListener.get();
977}
978
979EventHubInterface* InputReader::ContextImpl::getEventHub() {
980 return mReader->mEventHub.get();
981}
982
Prabir Pradhan42611e02018-11-27 14:04:02 -0800983uint32_t InputReader::ContextImpl::getNextSequenceNum() {
984 return (mReader->mNextSequenceNum)++;
985}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800986
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987// --- InputDevice ---
988
989InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
990 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
991 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
992 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700993 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800994}
995
996InputDevice::~InputDevice() {
997 size_t numMappers = mMappers.size();
998 for (size_t i = 0; i < numMappers; i++) {
999 delete mMappers[i];
1000 }
1001 mMappers.clear();
1002}
1003
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001004bool InputDevice::isEnabled() {
1005 return getEventHub()->isDeviceEnabled(mId);
1006}
1007
1008void InputDevice::setEnabled(bool enabled, nsecs_t when) {
1009 if (isEnabled() == enabled) {
1010 return;
1011 }
1012
1013 if (enabled) {
1014 getEventHub()->enableDevice(mId);
1015 reset(when);
1016 } else {
1017 reset(when);
1018 getEventHub()->disableDevice(mId);
1019 }
1020 // Must change generation to flag this device as changed
1021 bumpGeneration();
1022}
1023
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001024void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001025 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001026 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001027
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001028 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001029 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001030 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1031 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001032 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1033 if (mAssociatedDisplayPort) {
1034 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1035 } else {
1036 dump += "<none>\n";
1037 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001038 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1039 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1040 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001041
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001042 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1043 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001044 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001046 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001047 const char* label = getAxisLabel(range.axis);
1048 char name[32];
1049 if (label) {
1050 strncpy(name, label, sizeof(name));
1051 name[sizeof(name) - 1] = '\0';
1052 } else {
1053 snprintf(name, sizeof(name), "%d", range.axis);
1054 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001055 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1057 name, range.source, range.min, range.max, range.flat, range.fuzz,
1058 range.resolution);
1059 }
1060 }
1061
1062 size_t numMappers = mMappers.size();
1063 for (size_t i = 0; i < numMappers; i++) {
1064 InputMapper* mapper = mMappers[i];
1065 mapper->dump(dump);
1066 }
1067}
1068
1069void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001070 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001071}
1072
1073void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1074 mSources = 0;
1075
1076 if (!isIgnored()) {
1077 if (!changes) { // first time only
1078 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1079 }
1080
1081 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1082 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1083 sp<KeyCharacterMap> keyboardLayout =
1084 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1085 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1086 bumpGeneration();
1087 }
1088 }
1089 }
1090
1091 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1092 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001093 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 if (mAlias != alias) {
1095 mAlias = alias;
1096 bumpGeneration();
1097 }
1098 }
1099 }
1100
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001101 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
Siarhei Vishniakouc6f61192019-07-23 18:12:31 +00001102 auto it = config->disabledDevices.find(mId);
1103 bool enabled = it == config->disabledDevices.end();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001104 setEnabled(enabled, when);
1105 }
1106
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001107 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1108 // In most situations, no port will be specified.
1109 mAssociatedDisplayPort = std::nullopt;
1110 // Find the display port that corresponds to the current input port.
1111 const std::string& inputPort = mIdentifier.location;
1112 if (!inputPort.empty()) {
1113 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1114 const auto& displayPort = ports.find(inputPort);
1115 if (displayPort != ports.end()) {
1116 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1117 }
1118 }
1119 }
1120
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001121 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001122 mapper->configure(when, config, changes);
1123 mSources |= mapper->getSources();
1124 }
1125 }
1126}
1127
1128void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001129 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001130 mapper->reset(when);
1131 }
1132
1133 mContext->updateGlobalMetaState();
1134
1135 notifyReset(when);
1136}
1137
1138void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1139 // Process all of the events in order for each mapper.
1140 // We cannot simply ask each mapper to process them in bulk because mappers may
1141 // have side-effects that must be interleaved. For example, joystick movement events and
1142 // gamepad button presses are handled by different mappers but they should be dispatched
1143 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001144 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001145#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001146 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001147 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1148 rawEvent->when);
1149#endif
1150
1151 if (mDropUntilNextSync) {
1152 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1153 mDropUntilNextSync = false;
1154#if DEBUG_RAW_EVENTS
1155 ALOGD("Recovered from input event buffer overrun.");
1156#endif
1157 } else {
1158#if DEBUG_RAW_EVENTS
1159 ALOGD("Dropped input event while waiting for next input sync.");
1160#endif
1161 }
1162 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001163 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 mDropUntilNextSync = true;
1165 reset(rawEvent->when);
1166 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001167 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001168 mapper->process(rawEvent);
1169 }
1170 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001171 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001172 }
1173}
1174
1175void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001176 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001177 mapper->timeoutExpired(when);
1178 }
1179}
1180
Michael Wright842500e2015-03-13 17:32:02 -07001181void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001182 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001183 mapper->updateExternalStylusState(state);
1184 }
1185}
1186
Michael Wrightd02c5b62014-02-10 15:10:22 -08001187void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1188 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001189 mIsExternal, mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001190 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001191 mapper->populateDeviceInfo(outDeviceInfo);
1192 }
1193}
1194
1195int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1196 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1197}
1198
1199int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1200 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1201}
1202
1203int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1204 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1205}
1206
1207int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1208 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001209 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001210 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1211 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1212 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1213 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1214 if (currentResult >= AKEY_STATE_DOWN) {
1215 return currentResult;
1216 } else if (currentResult == AKEY_STATE_UP) {
1217 result = currentResult;
1218 }
1219 }
1220 }
1221 return result;
1222}
1223
1224bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1225 const int32_t* keyCodes, uint8_t* outFlags) {
1226 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001227 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001228 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1229 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1230 }
1231 }
1232 return result;
1233}
1234
1235void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1236 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001237 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238 mapper->vibrate(pattern, patternSize, repeat, token);
1239 }
1240}
1241
1242void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001243 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 mapper->cancelVibrate(token);
1245 }
1246}
1247
Jeff Brownc9aa6282015-02-11 19:03:28 -08001248void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001249 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001250 mapper->cancelTouch(when);
1251 }
1252}
1253
Michael Wrightd02c5b62014-02-10 15:10:22 -08001254int32_t InputDevice::getMetaState() {
1255 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001256 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257 result |= mapper->getMetaState();
1258 }
1259 return result;
1260}
1261
Andrii Kulian763a3a42016-03-08 10:46:16 -08001262void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001263 for (InputMapper* mapper : mMappers) {
1264 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001265 }
1266}
1267
Michael Wrightd02c5b62014-02-10 15:10:22 -08001268void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001269 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001270 mapper->fadePointer();
1271 }
1272}
1273
1274void InputDevice::bumpGeneration() {
1275 mGeneration = mContext->bumpGeneration();
1276}
1277
1278void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001279 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001280 mContext->getListener()->notifyDeviceReset(&args);
1281}
1282
Arthur Hungc23540e2018-11-29 20:42:11 +08001283std::optional<int32_t> InputDevice::getAssociatedDisplay() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001284 for (InputMapper* mapper : mMappers) {
Arthur Hungc23540e2018-11-29 20:42:11 +08001285 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplay();
1286 if (associatedDisplayId) {
1287 return associatedDisplayId;
1288 }
1289 }
1290
1291 return std::nullopt;
1292}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001293
1294// --- CursorButtonAccumulator ---
1295
1296CursorButtonAccumulator::CursorButtonAccumulator() {
1297 clearButtons();
1298}
1299
1300void CursorButtonAccumulator::reset(InputDevice* device) {
1301 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1302 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1303 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1304 mBtnBack = device->isKeyPressed(BTN_BACK);
1305 mBtnSide = device->isKeyPressed(BTN_SIDE);
1306 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1307 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1308 mBtnTask = device->isKeyPressed(BTN_TASK);
1309}
1310
1311void CursorButtonAccumulator::clearButtons() {
1312 mBtnLeft = 0;
1313 mBtnRight = 0;
1314 mBtnMiddle = 0;
1315 mBtnBack = 0;
1316 mBtnSide = 0;
1317 mBtnForward = 0;
1318 mBtnExtra = 0;
1319 mBtnTask = 0;
1320}
1321
1322void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1323 if (rawEvent->type == EV_KEY) {
1324 switch (rawEvent->code) {
1325 case BTN_LEFT:
1326 mBtnLeft = rawEvent->value;
1327 break;
1328 case BTN_RIGHT:
1329 mBtnRight = rawEvent->value;
1330 break;
1331 case BTN_MIDDLE:
1332 mBtnMiddle = rawEvent->value;
1333 break;
1334 case BTN_BACK:
1335 mBtnBack = rawEvent->value;
1336 break;
1337 case BTN_SIDE:
1338 mBtnSide = rawEvent->value;
1339 break;
1340 case BTN_FORWARD:
1341 mBtnForward = rawEvent->value;
1342 break;
1343 case BTN_EXTRA:
1344 mBtnExtra = rawEvent->value;
1345 break;
1346 case BTN_TASK:
1347 mBtnTask = rawEvent->value;
1348 break;
1349 }
1350 }
1351}
1352
1353uint32_t CursorButtonAccumulator::getButtonState() const {
1354 uint32_t result = 0;
1355 if (mBtnLeft) {
1356 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1357 }
1358 if (mBtnRight) {
1359 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1360 }
1361 if (mBtnMiddle) {
1362 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1363 }
1364 if (mBtnBack || mBtnSide) {
1365 result |= AMOTION_EVENT_BUTTON_BACK;
1366 }
1367 if (mBtnForward || mBtnExtra) {
1368 result |= AMOTION_EVENT_BUTTON_FORWARD;
1369 }
1370 return result;
1371}
1372
1373
1374// --- CursorMotionAccumulator ---
1375
1376CursorMotionAccumulator::CursorMotionAccumulator() {
1377 clearRelativeAxes();
1378}
1379
1380void CursorMotionAccumulator::reset(InputDevice* device) {
1381 clearRelativeAxes();
1382}
1383
1384void CursorMotionAccumulator::clearRelativeAxes() {
1385 mRelX = 0;
1386 mRelY = 0;
1387}
1388
1389void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1390 if (rawEvent->type == EV_REL) {
1391 switch (rawEvent->code) {
1392 case REL_X:
1393 mRelX = rawEvent->value;
1394 break;
1395 case REL_Y:
1396 mRelY = rawEvent->value;
1397 break;
1398 }
1399 }
1400}
1401
1402void CursorMotionAccumulator::finishSync() {
1403 clearRelativeAxes();
1404}
1405
1406
1407// --- CursorScrollAccumulator ---
1408
1409CursorScrollAccumulator::CursorScrollAccumulator() :
1410 mHaveRelWheel(false), mHaveRelHWheel(false) {
1411 clearRelativeAxes();
1412}
1413
1414void CursorScrollAccumulator::configure(InputDevice* device) {
1415 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1416 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1417}
1418
1419void CursorScrollAccumulator::reset(InputDevice* device) {
1420 clearRelativeAxes();
1421}
1422
1423void CursorScrollAccumulator::clearRelativeAxes() {
1424 mRelWheel = 0;
1425 mRelHWheel = 0;
1426}
1427
1428void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1429 if (rawEvent->type == EV_REL) {
1430 switch (rawEvent->code) {
1431 case REL_WHEEL:
1432 mRelWheel = rawEvent->value;
1433 break;
1434 case REL_HWHEEL:
1435 mRelHWheel = rawEvent->value;
1436 break;
1437 }
1438 }
1439}
1440
1441void CursorScrollAccumulator::finishSync() {
1442 clearRelativeAxes();
1443}
1444
1445
1446// --- TouchButtonAccumulator ---
1447
1448TouchButtonAccumulator::TouchButtonAccumulator() :
1449 mHaveBtnTouch(false), mHaveStylus(false) {
1450 clearButtons();
1451}
1452
1453void TouchButtonAccumulator::configure(InputDevice* device) {
1454 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1455 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1456 || device->hasKey(BTN_TOOL_RUBBER)
1457 || device->hasKey(BTN_TOOL_BRUSH)
1458 || device->hasKey(BTN_TOOL_PENCIL)
1459 || device->hasKey(BTN_TOOL_AIRBRUSH);
1460}
1461
1462void TouchButtonAccumulator::reset(InputDevice* device) {
1463 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1464 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001465 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1466 mBtnStylus2 =
1467 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1469 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1470 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1471 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1472 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1473 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1474 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1475 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1476 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1477 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1478 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1479}
1480
1481void TouchButtonAccumulator::clearButtons() {
1482 mBtnTouch = 0;
1483 mBtnStylus = 0;
1484 mBtnStylus2 = 0;
1485 mBtnToolFinger = 0;
1486 mBtnToolPen = 0;
1487 mBtnToolRubber = 0;
1488 mBtnToolBrush = 0;
1489 mBtnToolPencil = 0;
1490 mBtnToolAirbrush = 0;
1491 mBtnToolMouse = 0;
1492 mBtnToolLens = 0;
1493 mBtnToolDoubleTap = 0;
1494 mBtnToolTripleTap = 0;
1495 mBtnToolQuadTap = 0;
1496}
1497
1498void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1499 if (rawEvent->type == EV_KEY) {
1500 switch (rawEvent->code) {
1501 case BTN_TOUCH:
1502 mBtnTouch = rawEvent->value;
1503 break;
1504 case BTN_STYLUS:
1505 mBtnStylus = rawEvent->value;
1506 break;
1507 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001508 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001509 mBtnStylus2 = rawEvent->value;
1510 break;
1511 case BTN_TOOL_FINGER:
1512 mBtnToolFinger = rawEvent->value;
1513 break;
1514 case BTN_TOOL_PEN:
1515 mBtnToolPen = rawEvent->value;
1516 break;
1517 case BTN_TOOL_RUBBER:
1518 mBtnToolRubber = rawEvent->value;
1519 break;
1520 case BTN_TOOL_BRUSH:
1521 mBtnToolBrush = rawEvent->value;
1522 break;
1523 case BTN_TOOL_PENCIL:
1524 mBtnToolPencil = rawEvent->value;
1525 break;
1526 case BTN_TOOL_AIRBRUSH:
1527 mBtnToolAirbrush = rawEvent->value;
1528 break;
1529 case BTN_TOOL_MOUSE:
1530 mBtnToolMouse = rawEvent->value;
1531 break;
1532 case BTN_TOOL_LENS:
1533 mBtnToolLens = rawEvent->value;
1534 break;
1535 case BTN_TOOL_DOUBLETAP:
1536 mBtnToolDoubleTap = rawEvent->value;
1537 break;
1538 case BTN_TOOL_TRIPLETAP:
1539 mBtnToolTripleTap = rawEvent->value;
1540 break;
1541 case BTN_TOOL_QUADTAP:
1542 mBtnToolQuadTap = rawEvent->value;
1543 break;
1544 }
1545 }
1546}
1547
1548uint32_t TouchButtonAccumulator::getButtonState() const {
1549 uint32_t result = 0;
1550 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001551 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001552 }
1553 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001554 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001555 }
1556 return result;
1557}
1558
1559int32_t TouchButtonAccumulator::getToolType() const {
1560 if (mBtnToolMouse || mBtnToolLens) {
1561 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1562 }
1563 if (mBtnToolRubber) {
1564 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1565 }
1566 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1567 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1568 }
1569 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1570 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1571 }
1572 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1573}
1574
1575bool TouchButtonAccumulator::isToolActive() const {
1576 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1577 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1578 || mBtnToolMouse || mBtnToolLens
1579 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1580}
1581
1582bool TouchButtonAccumulator::isHovering() const {
1583 return mHaveBtnTouch && !mBtnTouch;
1584}
1585
1586bool TouchButtonAccumulator::hasStylus() const {
1587 return mHaveStylus;
1588}
1589
1590
1591// --- RawPointerAxes ---
1592
1593RawPointerAxes::RawPointerAxes() {
1594 clear();
1595}
1596
1597void RawPointerAxes::clear() {
1598 x.clear();
1599 y.clear();
1600 pressure.clear();
1601 touchMajor.clear();
1602 touchMinor.clear();
1603 toolMajor.clear();
1604 toolMinor.clear();
1605 orientation.clear();
1606 distance.clear();
1607 tiltX.clear();
1608 tiltY.clear();
1609 trackingId.clear();
1610 slot.clear();
1611}
1612
1613
1614// --- RawPointerData ---
1615
1616RawPointerData::RawPointerData() {
1617 clear();
1618}
1619
1620void RawPointerData::clear() {
1621 pointerCount = 0;
1622 clearIdBits();
1623}
1624
1625void RawPointerData::copyFrom(const RawPointerData& other) {
1626 pointerCount = other.pointerCount;
1627 hoveringIdBits = other.hoveringIdBits;
1628 touchingIdBits = other.touchingIdBits;
1629
1630 for (uint32_t i = 0; i < pointerCount; i++) {
1631 pointers[i] = other.pointers[i];
1632
1633 int id = pointers[i].id;
1634 idToIndex[id] = other.idToIndex[id];
1635 }
1636}
1637
1638void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1639 float x = 0, y = 0;
1640 uint32_t count = touchingIdBits.count();
1641 if (count) {
1642 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1643 uint32_t id = idBits.clearFirstMarkedBit();
1644 const Pointer& pointer = pointerForId(id);
1645 x += pointer.x;
1646 y += pointer.y;
1647 }
1648 x /= count;
1649 y /= count;
1650 }
1651 *outX = x;
1652 *outY = y;
1653}
1654
1655
1656// --- CookedPointerData ---
1657
1658CookedPointerData::CookedPointerData() {
1659 clear();
1660}
1661
1662void CookedPointerData::clear() {
1663 pointerCount = 0;
1664 hoveringIdBits.clear();
1665 touchingIdBits.clear();
1666}
1667
1668void CookedPointerData::copyFrom(const CookedPointerData& other) {
1669 pointerCount = other.pointerCount;
1670 hoveringIdBits = other.hoveringIdBits;
1671 touchingIdBits = other.touchingIdBits;
1672
1673 for (uint32_t i = 0; i < pointerCount; i++) {
1674 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1675 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1676
1677 int id = pointerProperties[i].id;
1678 idToIndex[id] = other.idToIndex[id];
1679 }
1680}
1681
1682
1683// --- SingleTouchMotionAccumulator ---
1684
1685SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1686 clearAbsoluteAxes();
1687}
1688
1689void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1690 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1691 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1692 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1693 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1694 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1695 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1696 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1697}
1698
1699void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1700 mAbsX = 0;
1701 mAbsY = 0;
1702 mAbsPressure = 0;
1703 mAbsToolWidth = 0;
1704 mAbsDistance = 0;
1705 mAbsTiltX = 0;
1706 mAbsTiltY = 0;
1707}
1708
1709void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1710 if (rawEvent->type == EV_ABS) {
1711 switch (rawEvent->code) {
1712 case ABS_X:
1713 mAbsX = rawEvent->value;
1714 break;
1715 case ABS_Y:
1716 mAbsY = rawEvent->value;
1717 break;
1718 case ABS_PRESSURE:
1719 mAbsPressure = rawEvent->value;
1720 break;
1721 case ABS_TOOL_WIDTH:
1722 mAbsToolWidth = rawEvent->value;
1723 break;
1724 case ABS_DISTANCE:
1725 mAbsDistance = rawEvent->value;
1726 break;
1727 case ABS_TILT_X:
1728 mAbsTiltX = rawEvent->value;
1729 break;
1730 case ABS_TILT_Y:
1731 mAbsTiltY = rawEvent->value;
1732 break;
1733 }
1734 }
1735}
1736
1737
1738// --- MultiTouchMotionAccumulator ---
1739
Atif Niyaz21da0ff2019-06-28 13:22:51 -07001740MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1741 : mCurrentSlot(-1),
1742 mSlots(nullptr),
1743 mSlotCount(0),
1744 mUsingSlotsProtocol(false),
1745 mHaveStylus(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001746
1747MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1748 delete[] mSlots;
1749}
1750
1751void MultiTouchMotionAccumulator::configure(InputDevice* device,
1752 size_t slotCount, bool usingSlotsProtocol) {
1753 mSlotCount = slotCount;
1754 mUsingSlotsProtocol = usingSlotsProtocol;
1755 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1756
1757 delete[] mSlots;
1758 mSlots = new Slot[slotCount];
1759}
1760
1761void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1762 // Unfortunately there is no way to read the initial contents of the slots.
1763 // So when we reset the accumulator, we must assume they are all zeroes.
1764 if (mUsingSlotsProtocol) {
1765 // Query the driver for the current slot index and use it as the initial slot
1766 // before we start reading events from the device. It is possible that the
1767 // current slot index will not be the same as it was when the first event was
1768 // written into the evdev buffer, which means the input mapper could start
1769 // out of sync with the initial state of the events in the evdev buffer.
1770 // In the extremely unlikely case that this happens, the data from
1771 // two slots will be confused until the next ABS_MT_SLOT event is received.
1772 // This can cause the touch point to "jump", but at least there will be
1773 // no stuck touches.
1774 int32_t initialSlot;
1775 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1776 ABS_MT_SLOT, &initialSlot);
1777 if (status) {
1778 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1779 initialSlot = -1;
1780 }
1781 clearSlots(initialSlot);
1782 } else {
1783 clearSlots(-1);
1784 }
1785}
1786
1787void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1788 if (mSlots) {
1789 for (size_t i = 0; i < mSlotCount; i++) {
1790 mSlots[i].clear();
1791 }
1792 }
1793 mCurrentSlot = initialSlot;
1794}
1795
1796void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1797 if (rawEvent->type == EV_ABS) {
1798 bool newSlot = false;
1799 if (mUsingSlotsProtocol) {
1800 if (rawEvent->code == ABS_MT_SLOT) {
1801 mCurrentSlot = rawEvent->value;
1802 newSlot = true;
1803 }
1804 } else if (mCurrentSlot < 0) {
1805 mCurrentSlot = 0;
1806 }
1807
1808 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1809#if DEBUG_POINTERS
1810 if (newSlot) {
1811 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001812 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001813 mCurrentSlot, mSlotCount - 1);
1814 }
1815#endif
1816 } else {
1817 Slot* slot = &mSlots[mCurrentSlot];
1818
1819 switch (rawEvent->code) {
1820 case ABS_MT_POSITION_X:
1821 slot->mInUse = true;
1822 slot->mAbsMTPositionX = rawEvent->value;
1823 break;
1824 case ABS_MT_POSITION_Y:
1825 slot->mInUse = true;
1826 slot->mAbsMTPositionY = rawEvent->value;
1827 break;
1828 case ABS_MT_TOUCH_MAJOR:
1829 slot->mInUse = true;
1830 slot->mAbsMTTouchMajor = rawEvent->value;
1831 break;
1832 case ABS_MT_TOUCH_MINOR:
1833 slot->mInUse = true;
1834 slot->mAbsMTTouchMinor = rawEvent->value;
1835 slot->mHaveAbsMTTouchMinor = true;
1836 break;
1837 case ABS_MT_WIDTH_MAJOR:
1838 slot->mInUse = true;
1839 slot->mAbsMTWidthMajor = rawEvent->value;
1840 break;
1841 case ABS_MT_WIDTH_MINOR:
1842 slot->mInUse = true;
1843 slot->mAbsMTWidthMinor = rawEvent->value;
1844 slot->mHaveAbsMTWidthMinor = true;
1845 break;
1846 case ABS_MT_ORIENTATION:
1847 slot->mInUse = true;
1848 slot->mAbsMTOrientation = rawEvent->value;
1849 break;
1850 case ABS_MT_TRACKING_ID:
1851 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1852 // The slot is no longer in use but it retains its previous contents,
1853 // which may be reused for subsequent touches.
1854 slot->mInUse = false;
1855 } else {
1856 slot->mInUse = true;
1857 slot->mAbsMTTrackingId = rawEvent->value;
1858 }
1859 break;
1860 case ABS_MT_PRESSURE:
1861 slot->mInUse = true;
1862 slot->mAbsMTPressure = rawEvent->value;
1863 break;
1864 case ABS_MT_DISTANCE:
1865 slot->mInUse = true;
1866 slot->mAbsMTDistance = rawEvent->value;
1867 break;
1868 case ABS_MT_TOOL_TYPE:
1869 slot->mInUse = true;
1870 slot->mAbsMTToolType = rawEvent->value;
1871 slot->mHaveAbsMTToolType = true;
1872 break;
1873 }
1874 }
1875 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1876 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1877 mCurrentSlot += 1;
1878 }
1879}
1880
1881void MultiTouchMotionAccumulator::finishSync() {
1882 if (!mUsingSlotsProtocol) {
1883 clearSlots(-1);
1884 }
1885}
1886
1887bool MultiTouchMotionAccumulator::hasStylus() const {
1888 return mHaveStylus;
1889}
1890
1891
1892// --- MultiTouchMotionAccumulator::Slot ---
1893
1894MultiTouchMotionAccumulator::Slot::Slot() {
1895 clear();
1896}
1897
1898void MultiTouchMotionAccumulator::Slot::clear() {
1899 mInUse = false;
1900 mHaveAbsMTTouchMinor = false;
1901 mHaveAbsMTWidthMinor = false;
1902 mHaveAbsMTToolType = false;
1903 mAbsMTPositionX = 0;
1904 mAbsMTPositionY = 0;
1905 mAbsMTTouchMajor = 0;
1906 mAbsMTTouchMinor = 0;
1907 mAbsMTWidthMajor = 0;
1908 mAbsMTWidthMinor = 0;
1909 mAbsMTOrientation = 0;
1910 mAbsMTTrackingId = -1;
1911 mAbsMTPressure = 0;
1912 mAbsMTDistance = 0;
1913 mAbsMTToolType = 0;
1914}
1915
1916int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1917 if (mHaveAbsMTToolType) {
1918 switch (mAbsMTToolType) {
1919 case MT_TOOL_FINGER:
1920 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1921 case MT_TOOL_PEN:
1922 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1923 }
1924 }
1925 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1926}
1927
1928
1929// --- InputMapper ---
1930
1931InputMapper::InputMapper(InputDevice* device) :
1932 mDevice(device), mContext(device->getContext()) {
1933}
1934
1935InputMapper::~InputMapper() {
1936}
1937
1938void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1939 info->addSource(getSources());
1940}
1941
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001942void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001943}
1944
1945void InputMapper::configure(nsecs_t when,
1946 const InputReaderConfiguration* config, uint32_t changes) {
1947}
1948
1949void InputMapper::reset(nsecs_t when) {
1950}
1951
1952void InputMapper::timeoutExpired(nsecs_t when) {
1953}
1954
1955int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1956 return AKEY_STATE_UNKNOWN;
1957}
1958
1959int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1960 return AKEY_STATE_UNKNOWN;
1961}
1962
1963int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1964 return AKEY_STATE_UNKNOWN;
1965}
1966
1967bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1968 const int32_t* keyCodes, uint8_t* outFlags) {
1969 return false;
1970}
1971
1972void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1973 int32_t token) {
1974}
1975
1976void InputMapper::cancelVibrate(int32_t token) {
1977}
1978
Jeff Brownc9aa6282015-02-11 19:03:28 -08001979void InputMapper::cancelTouch(nsecs_t when) {
1980}
1981
Michael Wrightd02c5b62014-02-10 15:10:22 -08001982int32_t InputMapper::getMetaState() {
1983 return 0;
1984}
1985
Andrii Kulian763a3a42016-03-08 10:46:16 -08001986void InputMapper::updateMetaState(int32_t keyCode) {
1987}
1988
Michael Wright842500e2015-03-13 17:32:02 -07001989void InputMapper::updateExternalStylusState(const StylusState& state) {
1990
1991}
1992
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993void InputMapper::fadePointer() {
1994}
1995
1996status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1997 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1998}
1999
2000void InputMapper::bumpGeneration() {
2001 mDevice->bumpGeneration();
2002}
2003
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002004void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005 const RawAbsoluteAxisInfo& axis, const char* name) {
2006 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002007 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
2009 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002010 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002011 }
2012}
2013
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002014void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2015 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2016 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2017 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2018 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002019}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020
2021// --- SwitchInputMapper ---
2022
2023SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002024 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002025}
2026
2027SwitchInputMapper::~SwitchInputMapper() {
2028}
2029
2030uint32_t SwitchInputMapper::getSources() {
2031 return AINPUT_SOURCE_SWITCH;
2032}
2033
2034void SwitchInputMapper::process(const RawEvent* rawEvent) {
2035 switch (rawEvent->type) {
2036 case EV_SW:
2037 processSwitch(rawEvent->code, rawEvent->value);
2038 break;
2039
2040 case EV_SYN:
2041 if (rawEvent->code == SYN_REPORT) {
2042 sync(rawEvent->when);
2043 }
2044 }
2045}
2046
2047void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2048 if (switchCode >= 0 && switchCode < 32) {
2049 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002050 mSwitchValues |= 1 << switchCode;
2051 } else {
2052 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054 mUpdatedSwitchMask |= 1 << switchCode;
2055 }
2056}
2057
2058void SwitchInputMapper::sync(nsecs_t when) {
2059 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002060 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002061 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2062 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002063 getListener()->notifySwitch(&args);
2064
Michael Wrightd02c5b62014-02-10 15:10:22 -08002065 mUpdatedSwitchMask = 0;
2066 }
2067}
2068
2069int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2070 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2071}
2072
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002073void SwitchInputMapper::dump(std::string& dump) {
2074 dump += INDENT2 "Switch Input Mapper:\n";
2075 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002076}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002077
2078// --- VibratorInputMapper ---
2079
2080VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2081 InputMapper(device), mVibrating(false) {
2082}
2083
2084VibratorInputMapper::~VibratorInputMapper() {
2085}
2086
2087uint32_t VibratorInputMapper::getSources() {
2088 return 0;
2089}
2090
2091void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2092 InputMapper::populateDeviceInfo(info);
2093
2094 info->setVibrator(true);
2095}
2096
2097void VibratorInputMapper::process(const RawEvent* rawEvent) {
2098 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2099}
2100
2101void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2102 int32_t token) {
2103#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002104 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002105 for (size_t i = 0; i < patternSize; i++) {
2106 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002107 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002108 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002109 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002111 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002112 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002113#endif
2114
2115 mVibrating = true;
2116 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2117 mPatternSize = patternSize;
2118 mRepeat = repeat;
2119 mToken = token;
2120 mIndex = -1;
2121
2122 nextStep();
2123}
2124
2125void VibratorInputMapper::cancelVibrate(int32_t token) {
2126#if DEBUG_VIBRATOR
2127 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2128#endif
2129
2130 if (mVibrating && mToken == token) {
2131 stopVibrating();
2132 }
2133}
2134
2135void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2136 if (mVibrating) {
2137 if (when >= mNextStepTime) {
2138 nextStep();
2139 } else {
2140 getContext()->requestTimeoutAtTime(mNextStepTime);
2141 }
2142 }
2143}
2144
2145void VibratorInputMapper::nextStep() {
2146 mIndex += 1;
2147 if (size_t(mIndex) >= mPatternSize) {
2148 if (mRepeat < 0) {
2149 // We are done.
2150 stopVibrating();
2151 return;
2152 }
2153 mIndex = mRepeat;
2154 }
2155
2156 bool vibratorOn = mIndex & 1;
2157 nsecs_t duration = mPattern[mIndex];
2158 if (vibratorOn) {
2159#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002160 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002161#endif
2162 getEventHub()->vibrate(getDeviceId(), duration);
2163 } else {
2164#if DEBUG_VIBRATOR
2165 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2166#endif
2167 getEventHub()->cancelVibrate(getDeviceId());
2168 }
2169 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2170 mNextStepTime = now + duration;
2171 getContext()->requestTimeoutAtTime(mNextStepTime);
2172#if DEBUG_VIBRATOR
2173 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2174#endif
2175}
2176
2177void VibratorInputMapper::stopVibrating() {
2178 mVibrating = false;
2179#if DEBUG_VIBRATOR
2180 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2181#endif
2182 getEventHub()->cancelVibrate(getDeviceId());
2183}
2184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002185void VibratorInputMapper::dump(std::string& dump) {
2186 dump += INDENT2 "Vibrator Input Mapper:\n";
2187 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002188}
2189
2190
2191// --- KeyboardInputMapper ---
2192
2193KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2194 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002195 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002196}
2197
2198KeyboardInputMapper::~KeyboardInputMapper() {
2199}
2200
2201uint32_t KeyboardInputMapper::getSources() {
2202 return mSource;
2203}
2204
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002205int32_t KeyboardInputMapper::getOrientation() {
2206 if (mViewport) {
2207 return mViewport->orientation;
2208 }
2209 return DISPLAY_ORIENTATION_0;
2210}
2211
2212int32_t KeyboardInputMapper::getDisplayId() {
2213 if (mViewport) {
2214 return mViewport->displayId;
2215 }
2216 return ADISPLAY_ID_NONE;
2217}
2218
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2220 InputMapper::populateDeviceInfo(info);
2221
2222 info->setKeyboardType(mKeyboardType);
2223 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2224}
2225
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002226void KeyboardInputMapper::dump(std::string& dump) {
2227 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002228 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002229 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002230 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002231 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2232 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2233 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234}
2235
Michael Wrightd02c5b62014-02-10 15:10:22 -08002236void KeyboardInputMapper::configure(nsecs_t when,
2237 const InputReaderConfiguration* config, uint32_t changes) {
2238 InputMapper::configure(when, config, changes);
2239
2240 if (!changes) { // first time only
2241 // Configure basic parameters.
2242 configureParameters();
2243 }
2244
2245 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002246 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002247 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002248 }
2249 }
2250}
2251
Ivan Podogovb9afef32017-02-13 15:34:32 +00002252static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2253 int32_t mapped = 0;
2254 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2255 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2256 if (stemKeyRotationMap[i][0] == keyCode) {
2257 stemKeyRotationMap[i][1] = mapped;
2258 return;
2259 }
2260 }
2261 }
2262}
2263
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264void KeyboardInputMapper::configureParameters() {
2265 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002266 const PropertyMap& config = getDevice()->getConfiguration();
2267 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 mParameters.orientationAware);
2269
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002271 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2272 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2273 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2274 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002275 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002276
2277 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002278 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002279 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002280}
2281
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002282void KeyboardInputMapper::dumpParameters(std::string& dump) {
2283 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002284 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002286 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002287 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002288}
2289
2290void KeyboardInputMapper::reset(nsecs_t when) {
2291 mMetaState = AMETA_NONE;
2292 mDownTime = 0;
2293 mKeyDowns.clear();
2294 mCurrentHidUsage = 0;
2295
2296 resetLedState();
2297
2298 InputMapper::reset(when);
2299}
2300
2301void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2302 switch (rawEvent->type) {
2303 case EV_KEY: {
2304 int32_t scanCode = rawEvent->code;
2305 int32_t usageCode = mCurrentHidUsage;
2306 mCurrentHidUsage = 0;
2307
2308 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002309 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002310 }
2311 break;
2312 }
2313 case EV_MSC: {
2314 if (rawEvent->code == MSC_SCAN) {
2315 mCurrentHidUsage = rawEvent->value;
2316 }
2317 break;
2318 }
2319 case EV_SYN: {
2320 if (rawEvent->code == SYN_REPORT) {
2321 mCurrentHidUsage = 0;
2322 }
2323 }
2324 }
2325}
2326
2327bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2328 return scanCode < BTN_MOUSE
2329 || scanCode >= KEY_OK
2330 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2331 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2332}
2333
Michael Wright58ba9882017-07-26 16:19:11 +01002334bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2335 switch (keyCode) {
2336 case AKEYCODE_MEDIA_PLAY:
2337 case AKEYCODE_MEDIA_PAUSE:
2338 case AKEYCODE_MEDIA_PLAY_PAUSE:
2339 case AKEYCODE_MUTE:
2340 case AKEYCODE_HEADSETHOOK:
2341 case AKEYCODE_MEDIA_STOP:
2342 case AKEYCODE_MEDIA_NEXT:
2343 case AKEYCODE_MEDIA_PREVIOUS:
2344 case AKEYCODE_MEDIA_REWIND:
2345 case AKEYCODE_MEDIA_RECORD:
2346 case AKEYCODE_MEDIA_FAST_FORWARD:
2347 case AKEYCODE_MEDIA_SKIP_FORWARD:
2348 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2349 case AKEYCODE_MEDIA_STEP_FORWARD:
2350 case AKEYCODE_MEDIA_STEP_BACKWARD:
2351 case AKEYCODE_MEDIA_AUDIO_TRACK:
2352 case AKEYCODE_VOLUME_UP:
2353 case AKEYCODE_VOLUME_DOWN:
2354 case AKEYCODE_VOLUME_MUTE:
2355 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2356 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2357 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2358 return true;
2359 }
2360 return false;
2361}
2362
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002363void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2364 int32_t usageCode) {
2365 int32_t keyCode;
2366 int32_t keyMetaState;
2367 uint32_t policyFlags;
2368
2369 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2370 &keyCode, &keyMetaState, &policyFlags)) {
2371 keyCode = AKEYCODE_UNKNOWN;
2372 keyMetaState = mMetaState;
2373 policyFlags = 0;
2374 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002375
2376 if (down) {
2377 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002378 if (mParameters.orientationAware) {
2379 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380 }
2381
2382 // Add key down.
2383 ssize_t keyDownIndex = findKeyDown(scanCode);
2384 if (keyDownIndex >= 0) {
2385 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002386 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002387 } else {
2388 // key down
2389 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2390 && mContext->shouldDropVirtualKey(when,
2391 getDevice(), keyCode, scanCode)) {
2392 return;
2393 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002394 if (policyFlags & POLICY_FLAG_GESTURE) {
2395 mDevice->cancelTouch(when);
2396 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002398 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 keyDown.keyCode = keyCode;
2400 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002401 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 }
2403
2404 mDownTime = when;
2405 } else {
2406 // Remove key down.
2407 ssize_t keyDownIndex = findKeyDown(scanCode);
2408 if (keyDownIndex >= 0) {
2409 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002410 keyCode = mKeyDowns[keyDownIndex].keyCode;
2411 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 } else {
2413 // key was not actually down
2414 ALOGI("Dropping key up from device %s because the key was not down. "
2415 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002416 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 return;
2418 }
2419 }
2420
Andrii Kulian763a3a42016-03-08 10:46:16 -08002421 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002422 // If global meta state changed send it along with the key.
2423 // If it has not changed then we'll use what keymap gave us,
2424 // since key replacement logic might temporarily reset a few
2425 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002426 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 }
2428
2429 nsecs_t downTime = mDownTime;
2430
2431 // Key down on external an keyboard should wake the device.
2432 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2433 // For internal keyboards, the key layout file should specify the policy flags for
2434 // each wake key individually.
2435 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002436 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002437 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002438 }
2439
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002440 if (mParameters.handlesKeyRepeat) {
2441 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2442 }
2443
Prabir Pradhan42611e02018-11-27 14:04:02 -08002444 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2445 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002446 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002447 getListener()->notifyKey(&args);
2448}
2449
2450ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2451 size_t n = mKeyDowns.size();
2452 for (size_t i = 0; i < n; i++) {
2453 if (mKeyDowns[i].scanCode == scanCode) {
2454 return i;
2455 }
2456 }
2457 return -1;
2458}
2459
2460int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2461 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2462}
2463
2464int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2465 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2466}
2467
2468bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2469 const int32_t* keyCodes, uint8_t* outFlags) {
2470 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2471}
2472
2473int32_t KeyboardInputMapper::getMetaState() {
2474 return mMetaState;
2475}
2476
Andrii Kulian763a3a42016-03-08 10:46:16 -08002477void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2478 updateMetaStateIfNeeded(keyCode, false);
2479}
2480
2481bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2482 int32_t oldMetaState = mMetaState;
2483 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2484 bool metaStateChanged = oldMetaState != newMetaState;
2485 if (metaStateChanged) {
2486 mMetaState = newMetaState;
2487 updateLedState(false);
2488
2489 getContext()->updateGlobalMetaState();
2490 }
2491
2492 return metaStateChanged;
2493}
2494
Michael Wrightd02c5b62014-02-10 15:10:22 -08002495void KeyboardInputMapper::resetLedState() {
2496 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2497 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2498 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2499
2500 updateLedState(true);
2501}
2502
2503void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2504 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2505 ledState.on = false;
2506}
2507
2508void KeyboardInputMapper::updateLedState(bool reset) {
2509 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2510 AMETA_CAPS_LOCK_ON, reset);
2511 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2512 AMETA_NUM_LOCK_ON, reset);
2513 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2514 AMETA_SCROLL_LOCK_ON, reset);
2515}
2516
2517void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2518 int32_t led, int32_t modifier, bool reset) {
2519 if (ledState.avail) {
2520 bool desiredState = (mMetaState & modifier) != 0;
2521 if (reset || ledState.on != desiredState) {
2522 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2523 ledState.on = desiredState;
2524 }
2525 }
2526}
2527
2528
2529// --- CursorInputMapper ---
2530
2531CursorInputMapper::CursorInputMapper(InputDevice* device) :
2532 InputMapper(device) {
2533}
2534
2535CursorInputMapper::~CursorInputMapper() {
2536}
2537
2538uint32_t CursorInputMapper::getSources() {
2539 return mSource;
2540}
2541
2542void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2543 InputMapper::populateDeviceInfo(info);
2544
2545 if (mParameters.mode == Parameters::MODE_POINTER) {
2546 float minX, minY, maxX, maxY;
2547 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2548 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2549 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2550 }
2551 } else {
2552 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2553 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2554 }
2555 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2556
2557 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2558 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2559 }
2560 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2561 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2562 }
2563}
2564
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002565void CursorInputMapper::dump(std::string& dump) {
2566 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002567 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002568 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2569 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2570 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2571 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2572 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002573 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002574 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002575 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002576 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2577 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2578 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2579 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2580 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2581 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002582}
2583
2584void CursorInputMapper::configure(nsecs_t when,
2585 const InputReaderConfiguration* config, uint32_t changes) {
2586 InputMapper::configure(when, config, changes);
2587
2588 if (!changes) { // first time only
2589 mCursorScrollAccumulator.configure(getDevice());
2590
2591 // Configure basic parameters.
2592 configureParameters();
2593
2594 // Configure device mode.
2595 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002596 case Parameters::MODE_POINTER_RELATIVE:
2597 // Should not happen during first time configuration.
2598 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2599 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002600 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002601 case Parameters::MODE_POINTER:
2602 mSource = AINPUT_SOURCE_MOUSE;
2603 mXPrecision = 1.0f;
2604 mYPrecision = 1.0f;
2605 mXScale = 1.0f;
2606 mYScale = 1.0f;
2607 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2608 break;
2609 case Parameters::MODE_NAVIGATION:
2610 mSource = AINPUT_SOURCE_TRACKBALL;
2611 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2612 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2613 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2614 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2615 break;
2616 }
2617
2618 mVWheelScale = 1.0f;
2619 mHWheelScale = 1.0f;
2620 }
2621
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002622 if ((!changes && config->pointerCapture)
2623 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2624 if (config->pointerCapture) {
2625 if (mParameters.mode == Parameters::MODE_POINTER) {
2626 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2627 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2628 // Keep PointerController around in order to preserve the pointer position.
2629 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2630 } else {
2631 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2632 }
2633 } else {
2634 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2635 mParameters.mode = Parameters::MODE_POINTER;
2636 mSource = AINPUT_SOURCE_MOUSE;
2637 } else {
2638 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2639 }
2640 }
2641 bumpGeneration();
2642 if (changes) {
2643 getDevice()->notifyReset(when);
2644 }
2645 }
2646
Michael Wrightd02c5b62014-02-10 15:10:22 -08002647 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2648 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2649 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2650 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2651 }
2652
2653 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002654 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002655 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002656 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002657 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002658 if (internalViewport) {
2659 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002661 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002662
2663 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002664 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002665 getPolicy()->obtainPointerController(getDeviceId());
2666 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002667 bumpGeneration();
2668 }
2669}
2670
2671void CursorInputMapper::configureParameters() {
2672 mParameters.mode = Parameters::MODE_POINTER;
2673 String8 cursorModeString;
2674 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2675 if (cursorModeString == "navigation") {
2676 mParameters.mode = Parameters::MODE_NAVIGATION;
2677 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2678 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2679 }
2680 }
2681
2682 mParameters.orientationAware = false;
2683 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2684 mParameters.orientationAware);
2685
2686 mParameters.hasAssociatedDisplay = false;
2687 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2688 mParameters.hasAssociatedDisplay = true;
2689 }
2690}
2691
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002692void CursorInputMapper::dumpParameters(std::string& dump) {
2693 dump += INDENT3 "Parameters:\n";
2694 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695 toString(mParameters.hasAssociatedDisplay));
2696
2697 switch (mParameters.mode) {
2698 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002699 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002700 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002701 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002702 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002703 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002704 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002705 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706 break;
2707 default:
2708 ALOG_ASSERT(false);
2709 }
2710
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002711 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002712 toString(mParameters.orientationAware));
2713}
2714
2715void CursorInputMapper::reset(nsecs_t when) {
2716 mButtonState = 0;
2717 mDownTime = 0;
2718
2719 mPointerVelocityControl.reset();
2720 mWheelXVelocityControl.reset();
2721 mWheelYVelocityControl.reset();
2722
2723 mCursorButtonAccumulator.reset(getDevice());
2724 mCursorMotionAccumulator.reset(getDevice());
2725 mCursorScrollAccumulator.reset(getDevice());
2726
2727 InputMapper::reset(when);
2728}
2729
2730void CursorInputMapper::process(const RawEvent* rawEvent) {
2731 mCursorButtonAccumulator.process(rawEvent);
2732 mCursorMotionAccumulator.process(rawEvent);
2733 mCursorScrollAccumulator.process(rawEvent);
2734
2735 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2736 sync(rawEvent->when);
2737 }
2738}
2739
2740void CursorInputMapper::sync(nsecs_t when) {
2741 int32_t lastButtonState = mButtonState;
2742 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2743 mButtonState = currentButtonState;
2744
2745 bool wasDown = isPointerDown(lastButtonState);
2746 bool down = isPointerDown(currentButtonState);
2747 bool downChanged;
2748 if (!wasDown && down) {
2749 mDownTime = when;
2750 downChanged = true;
2751 } else if (wasDown && !down) {
2752 downChanged = true;
2753 } else {
2754 downChanged = false;
2755 }
2756 nsecs_t downTime = mDownTime;
2757 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002758 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2759 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760
2761 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2762 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2763 bool moved = deltaX != 0 || deltaY != 0;
2764
2765 // Rotate delta according to orientation if needed.
2766 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2767 && (deltaX != 0.0f || deltaY != 0.0f)) {
2768 rotateDelta(mOrientation, &deltaX, &deltaY);
2769 }
2770
2771 // Move the pointer.
2772 PointerProperties pointerProperties;
2773 pointerProperties.clear();
2774 pointerProperties.id = 0;
2775 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2776
2777 PointerCoords pointerCoords;
2778 pointerCoords.clear();
2779
2780 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2781 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2782 bool scrolled = vscroll != 0 || hscroll != 0;
2783
Yi Kong9b14ac62018-07-17 13:48:38 -07002784 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2785 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786
2787 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2788
2789 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002790 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2791 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002792 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002793 if (moved || scrolled || buttonsChanged) {
2794 mPointerController->setPresentation(
2795 PointerControllerInterface::PRESENTATION_POINTER);
2796
2797 if (moved) {
2798 mPointerController->move(deltaX, deltaY);
2799 }
2800
2801 if (buttonsChanged) {
2802 mPointerController->setButtonState(currentButtonState);
2803 }
2804
2805 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2806 }
2807
Garfield Tan00f511d2019-06-12 16:55:40 -07002808 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2809 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2810 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002811 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2812 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002813 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002814 } else {
2815 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2816 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2817 displayId = ADISPLAY_ID_NONE;
2818 }
2819
2820 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2821
2822 // Moving an external trackball or mouse should wake the device.
2823 // We don't do this for internal cursor devices to prevent them from waking up
2824 // the device in your pocket.
2825 // TODO: Use the input device configuration to control this behavior more finely.
2826 uint32_t policyFlags = 0;
2827 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002828 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002829 }
2830
2831 // Synthesize key down from buttons if needed.
2832 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002833 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002834
2835 // Send motion event.
2836 if (downChanged || moved || scrolled || buttonsChanged) {
2837 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002838 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 int32_t motionEventAction;
2840 if (downChanged) {
2841 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002842 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2844 } else {
2845 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2846 }
2847
Michael Wright7b159c92015-05-14 14:48:03 +01002848 if (buttonsReleased) {
2849 BitSet32 released(buttonsReleased);
2850 while (!released.isEmpty()) {
2851 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2852 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002853 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002854 mSource, displayId, policyFlags,
2855 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2856 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002857 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002858 &pointerCoords, mXPrecision, mYPrecision,
2859 xCursorPosition, yCursorPosition, downTime,
2860 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002861 getListener()->notifyMotion(&releaseArgs);
2862 }
2863 }
2864
Prabir Pradhan42611e02018-11-27 14:04:02 -08002865 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Garfield Tan00f511d2019-06-12 16:55:40 -07002866 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2867 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002868 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
Garfield Tan00f511d2019-06-12 16:55:40 -07002869 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2870 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 getListener()->notifyMotion(&args);
2872
Michael Wright7b159c92015-05-14 14:48:03 +01002873 if (buttonsPressed) {
2874 BitSet32 pressed(buttonsPressed);
2875 while (!pressed.isEmpty()) {
2876 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2877 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002878 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002879 mSource, displayId, policyFlags,
2880 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2881 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002882 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002883 &pointerCoords, mXPrecision, mYPrecision,
2884 xCursorPosition, yCursorPosition, downTime,
2885 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002886 getListener()->notifyMotion(&pressArgs);
2887 }
2888 }
2889
2890 ALOG_ASSERT(buttonState == currentButtonState);
2891
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 // Send hover move after UP to tell the application that the mouse is hovering now.
2893 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002894 && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002895 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2896 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2897 0, metaState, currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002898 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002899 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002900 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 getListener()->notifyMotion(&hoverArgs);
2902 }
2903
2904 // Send scroll events.
2905 if (scrolled) {
2906 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2907 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2908
Prabir Pradhan42611e02018-11-27 14:04:02 -08002909 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002910 mSource, displayId, policyFlags,
2911 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2912 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002913 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002914 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002915 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002916 getListener()->notifyMotion(&scrollArgs);
2917 }
2918 }
2919
2920 // Synthesize key up from buttons if needed.
2921 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002922 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923
2924 mCursorMotionAccumulator.finishSync();
2925 mCursorScrollAccumulator.finishSync();
2926}
2927
2928int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2929 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2930 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2931 } else {
2932 return AKEY_STATE_UNKNOWN;
2933 }
2934}
2935
2936void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002937 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002938 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2939 }
2940}
2941
Arthur Hungc23540e2018-11-29 20:42:11 +08002942std::optional<int32_t> CursorInputMapper::getAssociatedDisplay() {
2943 if (mParameters.hasAssociatedDisplay) {
2944 if (mParameters.mode == Parameters::MODE_POINTER) {
2945 return std::make_optional(mPointerController->getDisplayId());
2946 } else {
2947 // If the device is orientationAware and not a mouse,
2948 // it expects to dispatch events to any display
2949 return std::make_optional(ADISPLAY_ID_NONE);
2950 }
2951 }
2952 return std::nullopt;
2953}
2954
Prashant Malani1941ff52015-08-11 18:29:28 -07002955// --- RotaryEncoderInputMapper ---
2956
2957RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002958 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002959 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2960}
2961
2962RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2963}
2964
2965uint32_t RotaryEncoderInputMapper::getSources() {
2966 return mSource;
2967}
2968
2969void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2970 InputMapper::populateDeviceInfo(info);
2971
2972 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002973 float res = 0.0f;
2974 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2975 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2976 }
2977 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2978 mScalingFactor)) {
2979 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2980 "default to 1.0!\n");
2981 mScalingFactor = 1.0f;
2982 }
2983 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2984 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002985 }
2986}
2987
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002988void RotaryEncoderInputMapper::dump(std::string& dump) {
2989 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2990 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002991 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2992}
2993
2994void RotaryEncoderInputMapper::configure(nsecs_t when,
2995 const InputReaderConfiguration* config, uint32_t changes) {
2996 InputMapper::configure(when, config, changes);
2997 if (!changes) {
2998 mRotaryEncoderScrollAccumulator.configure(getDevice());
2999 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003000 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003001 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003002 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003003 if (internalViewport) {
3004 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003005 } else {
3006 mOrientation = DISPLAY_ORIENTATION_0;
3007 }
3008 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003009}
3010
3011void RotaryEncoderInputMapper::reset(nsecs_t when) {
3012 mRotaryEncoderScrollAccumulator.reset(getDevice());
3013
3014 InputMapper::reset(when);
3015}
3016
3017void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3018 mRotaryEncoderScrollAccumulator.process(rawEvent);
3019
3020 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3021 sync(rawEvent->when);
3022 }
3023}
3024
3025void RotaryEncoderInputMapper::sync(nsecs_t when) {
3026 PointerCoords pointerCoords;
3027 pointerCoords.clear();
3028
3029 PointerProperties pointerProperties;
3030 pointerProperties.clear();
3031 pointerProperties.id = 0;
3032 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3033
3034 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3035 bool scrolled = scroll != 0;
3036
3037 // This is not a pointer, so it's not associated with a display.
3038 int32_t displayId = ADISPLAY_ID_NONE;
3039
3040 // Moving the rotary encoder should wake the device (if specified).
3041 uint32_t policyFlags = 0;
3042 if (scrolled && getDevice()->isExternal()) {
3043 policyFlags |= POLICY_FLAG_WAKE;
3044 }
3045
Ivan Podogovad437252016-09-29 16:29:55 +01003046 if (mOrientation == DISPLAY_ORIENTATION_180) {
3047 scroll = -scroll;
3048 }
3049
Prashant Malani1941ff52015-08-11 18:29:28 -07003050 // Send motion event.
3051 if (scrolled) {
3052 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003053 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003054
Garfield Tan00f511d2019-06-12 16:55:40 -07003055 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3056 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3057 metaState, /* buttonState */ 0, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07003058 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
3059 &pointerCoords, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Garfield Tan00f511d2019-06-12 16:55:40 -07003060 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003061 getListener()->notifyMotion(&scrollArgs);
3062 }
3063
3064 mRotaryEncoderScrollAccumulator.finishSync();
3065}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003066
3067// --- TouchInputMapper ---
3068
3069TouchInputMapper::TouchInputMapper(InputDevice* device) :
3070 InputMapper(device),
3071 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3072 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003073 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003074 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3075}
3076
3077TouchInputMapper::~TouchInputMapper() {
3078}
3079
3080uint32_t TouchInputMapper::getSources() {
3081 return mSource;
3082}
3083
3084void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3085 InputMapper::populateDeviceInfo(info);
3086
3087 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3088 info->addMotionRange(mOrientedRanges.x);
3089 info->addMotionRange(mOrientedRanges.y);
3090 info->addMotionRange(mOrientedRanges.pressure);
3091
3092 if (mOrientedRanges.haveSize) {
3093 info->addMotionRange(mOrientedRanges.size);
3094 }
3095
3096 if (mOrientedRanges.haveTouchSize) {
3097 info->addMotionRange(mOrientedRanges.touchMajor);
3098 info->addMotionRange(mOrientedRanges.touchMinor);
3099 }
3100
3101 if (mOrientedRanges.haveToolSize) {
3102 info->addMotionRange(mOrientedRanges.toolMajor);
3103 info->addMotionRange(mOrientedRanges.toolMinor);
3104 }
3105
3106 if (mOrientedRanges.haveOrientation) {
3107 info->addMotionRange(mOrientedRanges.orientation);
3108 }
3109
3110 if (mOrientedRanges.haveDistance) {
3111 info->addMotionRange(mOrientedRanges.distance);
3112 }
3113
3114 if (mOrientedRanges.haveTilt) {
3115 info->addMotionRange(mOrientedRanges.tilt);
3116 }
3117
3118 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3119 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3120 0.0f);
3121 }
3122 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3123 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3124 0.0f);
3125 }
3126 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3127 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3128 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3129 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3130 x.fuzz, x.resolution);
3131 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3132 y.fuzz, y.resolution);
3133 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3134 x.fuzz, x.resolution);
3135 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3136 y.fuzz, y.resolution);
3137 }
3138 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3139 }
3140}
3141
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003142void TouchInputMapper::dump(std::string& dump) {
3143 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 dumpParameters(dump);
3145 dumpVirtualKeys(dump);
3146 dumpRawPointerAxes(dump);
3147 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003148 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 dumpSurface(dump);
3150
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003151 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3152 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3153 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3154 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3155 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3156 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3157 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3158 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3159 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3160 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3161 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3162 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3163 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3164 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3165 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3166 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3167 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003168
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003169 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3170 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003171 mLastRawState.rawPointerData.pointerCount);
3172 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3173 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3176 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3177 "toolType=%d, isHovering=%s\n", i,
3178 pointer.id, pointer.x, pointer.y, pointer.pressure,
3179 pointer.touchMajor, pointer.touchMinor,
3180 pointer.toolMajor, pointer.toolMinor,
3181 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3182 pointer.toolType, toString(pointer.isHovering));
3183 }
3184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003185 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3186 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003187 mLastCookedState.cookedPointerData.pointerCount);
3188 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3189 const PointerProperties& pointerProperties =
3190 mLastCookedState.cookedPointerData.pointerProperties[i];
3191 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003192 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3194 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3195 "toolType=%d, isHovering=%s\n", i,
3196 pointerProperties.id,
3197 pointerCoords.getX(),
3198 pointerCoords.getY(),
3199 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3200 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3201 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3202 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3203 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3204 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3205 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3206 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3207 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003208 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003209 }
3210
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003211 dump += INDENT3 "Stylus Fusion:\n";
3212 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003213 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003214 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3215 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003216 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003217 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003218 dumpStylusState(dump, mExternalStylusState);
3219
Michael Wrightd02c5b62014-02-10 15:10:22 -08003220 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003221 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3222 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003223 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003224 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003225 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003226 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003228 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003229 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003230 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003231 mPointerGestureMaxSwipeWidth);
3232 }
3233}
3234
Santos Cordonfa5cf462017-04-05 10:37:00 -07003235const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3236 switch (deviceMode) {
3237 case DEVICE_MODE_DISABLED:
3238 return "disabled";
3239 case DEVICE_MODE_DIRECT:
3240 return "direct";
3241 case DEVICE_MODE_UNSCALED:
3242 return "unscaled";
3243 case DEVICE_MODE_NAVIGATION:
3244 return "navigation";
3245 case DEVICE_MODE_POINTER:
3246 return "pointer";
3247 }
3248 return "unknown";
3249}
3250
Michael Wrightd02c5b62014-02-10 15:10:22 -08003251void TouchInputMapper::configure(nsecs_t when,
3252 const InputReaderConfiguration* config, uint32_t changes) {
3253 InputMapper::configure(when, config, changes);
3254
3255 mConfig = *config;
3256
3257 if (!changes) { // first time only
3258 // Configure basic parameters.
3259 configureParameters();
3260
3261 // Configure common accumulators.
3262 mCursorScrollAccumulator.configure(getDevice());
3263 mTouchButtonAccumulator.configure(getDevice());
3264
3265 // Configure absolute axis information.
3266 configureRawPointerAxes();
3267
3268 // Prepare input device calibration.
3269 parseCalibration();
3270 resolveCalibration();
3271 }
3272
Michael Wright842500e2015-03-13 17:32:02 -07003273 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003274 // Update location calibration to reflect current settings
3275 updateAffineTransformation();
3276 }
3277
Michael Wrightd02c5b62014-02-10 15:10:22 -08003278 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3279 // Update pointer speed.
3280 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3281 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3282 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3283 }
3284
3285 bool resetNeeded = false;
3286 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3287 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003288 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3289 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003290 // Configure device sources, surface dimensions, orientation and
3291 // scaling factors.
3292 configureSurface(when, &resetNeeded);
3293 }
3294
3295 if (changes && resetNeeded) {
3296 // Send reset, unless this is the first time the device has been configured,
3297 // in which case the reader will call reset itself after all mappers are ready.
3298 getDevice()->notifyReset(when);
3299 }
3300}
3301
Michael Wright842500e2015-03-13 17:32:02 -07003302void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003303 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003304 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003305 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003306
3307 if (!mExternalStylusConnected) {
3308 resetExternalStylus();
3309 }
3310}
3311
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312void TouchInputMapper::configureParameters() {
3313 // Use the pointer presentation mode for devices that do not support distinct
3314 // multitouch. The spot-based presentation relies on being able to accurately
3315 // locate two or more fingers on the touch pad.
3316 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003317 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003318
3319 String8 gestureModeString;
3320 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3321 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003322 if (gestureModeString == "single-touch") {
3323 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3324 } else if (gestureModeString == "multi-touch") {
3325 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326 } else if (gestureModeString != "default") {
3327 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3328 }
3329 }
3330
3331 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3332 // The device is a touch screen.
3333 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3334 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3335 // The device is a pointing device like a track pad.
3336 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3337 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3338 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3339 // The device is a cursor device with a touch pad attached.
3340 // By default don't use the touch pad to move the pointer.
3341 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3342 } else {
3343 // The device is a touch pad of unknown purpose.
3344 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3345 }
3346
3347 mParameters.hasButtonUnderPad=
3348 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3349
3350 String8 deviceTypeString;
3351 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3352 deviceTypeString)) {
3353 if (deviceTypeString == "touchScreen") {
3354 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3355 } else if (deviceTypeString == "touchPad") {
3356 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3357 } else if (deviceTypeString == "touchNavigation") {
3358 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3359 } else if (deviceTypeString == "pointer") {
3360 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3361 } else if (deviceTypeString != "default") {
3362 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3363 }
3364 }
3365
3366 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3367 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3368 mParameters.orientationAware);
3369
3370 mParameters.hasAssociatedDisplay = false;
3371 mParameters.associatedDisplayIsExternal = false;
3372 if (mParameters.orientationAware
3373 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3374 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3375 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003376 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3377 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003378 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003379 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003380 uniqueDisplayId);
3381 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003382 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003384 if (getDevice()->getAssociatedDisplayPort()) {
3385 mParameters.hasAssociatedDisplay = true;
3386 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003387
3388 // Initial downs on external touch devices should wake the device.
3389 // Normally we don't do this for internal touch screens to prevent them from waking
3390 // up in your pocket but you can enable it using the input device configuration.
3391 mParameters.wake = getDevice()->isExternal();
3392 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3393 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003394}
3395
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003396void TouchInputMapper::dumpParameters(std::string& dump) {
3397 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003398
3399 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003400 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003401 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003402 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003403 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003404 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 break;
3406 default:
3407 assert(false);
3408 }
3409
3410 switch (mParameters.deviceType) {
3411 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003412 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003413 break;
3414 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003415 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003416 break;
3417 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003418 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003419 break;
3420 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003421 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 break;
3423 default:
3424 ALOG_ASSERT(false);
3425 }
3426
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003427 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003428 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003430 toString(mParameters.associatedDisplayIsExternal),
3431 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003432 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003433 toString(mParameters.orientationAware));
3434}
3435
3436void TouchInputMapper::configureRawPointerAxes() {
3437 mRawPointerAxes.clear();
3438}
3439
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003440void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3441 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003442 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3443 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3444 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3445 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3446 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3447 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3455}
3456
Michael Wright842500e2015-03-13 17:32:02 -07003457bool TouchInputMapper::hasExternalStylus() const {
3458 return mExternalStylusConnected;
3459}
3460
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003461/**
3462 * Determine which DisplayViewport to use.
3463 * 1. If display port is specified, return the matching viewport. If matching viewport not
3464 * found, then return.
3465 * 2. If a device has associated display, get the matching viewport by either unique id or by
3466 * the display type (internal or external).
3467 * 3. Otherwise, use a non-display viewport.
3468 */
3469std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3470 if (mParameters.hasAssociatedDisplay) {
3471 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3472 if (displayPort) {
3473 // Find the viewport that contains the same port
3474 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3475 if (!v) {
3476 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3477 "but the corresponding viewport is not found.",
3478 getDeviceName().c_str(), *displayPort);
3479 }
3480 return v;
3481 }
3482
3483 if (!mParameters.uniqueDisplayId.empty()) {
3484 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3485 }
3486
3487 ViewportType viewportTypeToUse;
3488 if (mParameters.associatedDisplayIsExternal) {
3489 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3490 } else {
3491 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3492 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003493
3494 std::optional<DisplayViewport> viewport =
3495 mConfig.getDisplayViewportByType(viewportTypeToUse);
3496 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3497 ALOGW("Input device %s should be associated with external display, "
3498 "fallback to internal one for the external viewport is not found.",
3499 getDeviceName().c_str());
3500 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3501 }
3502
3503 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003504 }
3505
3506 DisplayViewport newViewport;
3507 // Raw width and height in the natural orientation.
3508 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3509 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3510 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3511 return std::make_optional(newViewport);
3512}
3513
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3515 int32_t oldDeviceMode = mDeviceMode;
3516
Michael Wright842500e2015-03-13 17:32:02 -07003517 resolveExternalStylusPresence();
3518
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 // Determine device mode.
3520 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3521 && mConfig.pointerGesturesEnabled) {
3522 mSource = AINPUT_SOURCE_MOUSE;
3523 mDeviceMode = DEVICE_MODE_POINTER;
3524 if (hasStylus()) {
3525 mSource |= AINPUT_SOURCE_STYLUS;
3526 }
3527 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3528 && mParameters.hasAssociatedDisplay) {
3529 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3530 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003531 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 mSource |= AINPUT_SOURCE_STYLUS;
3533 }
Michael Wright2f78b682015-06-12 15:25:08 +01003534 if (hasExternalStylus()) {
3535 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3536 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003537 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3538 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3539 mDeviceMode = DEVICE_MODE_NAVIGATION;
3540 } else {
3541 mSource = AINPUT_SOURCE_TOUCHPAD;
3542 mDeviceMode = DEVICE_MODE_UNSCALED;
3543 }
3544
3545 // Ensure we have valid X and Y axes.
3546 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003547 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003548 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003549 mDeviceMode = DEVICE_MODE_DISABLED;
3550 return;
3551 }
3552
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003553 // Get associated display dimensions.
3554 std::optional<DisplayViewport> newViewport = findViewport();
3555 if (!newViewport) {
3556 ALOGI("Touch device '%s' could not query the properties of its associated "
3557 "display. The device will be inoperable until the display size "
3558 "becomes available.",
3559 getDeviceName().c_str());
3560 mDeviceMode = DEVICE_MODE_DISABLED;
3561 return;
3562 }
3563
Michael Wrightd02c5b62014-02-10 15:10:22 -08003564 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003565 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3566 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003568 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003569 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003570 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003571
3572 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3573 // Convert rotated viewport to natural surface coordinates.
3574 int32_t naturalLogicalWidth, naturalLogicalHeight;
3575 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3576 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3577 int32_t naturalDeviceWidth, naturalDeviceHeight;
3578 switch (mViewport.orientation) {
3579 case DISPLAY_ORIENTATION_90:
3580 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3581 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3582 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3583 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3584 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3585 naturalPhysicalTop = mViewport.physicalLeft;
3586 naturalDeviceWidth = mViewport.deviceHeight;
3587 naturalDeviceHeight = mViewport.deviceWidth;
3588 break;
3589 case DISPLAY_ORIENTATION_180:
3590 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3591 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3592 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3593 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3594 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3595 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3596 naturalDeviceWidth = mViewport.deviceWidth;
3597 naturalDeviceHeight = mViewport.deviceHeight;
3598 break;
3599 case DISPLAY_ORIENTATION_270:
3600 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3601 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3602 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3603 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3604 naturalPhysicalLeft = mViewport.physicalTop;
3605 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3606 naturalDeviceWidth = mViewport.deviceHeight;
3607 naturalDeviceHeight = mViewport.deviceWidth;
3608 break;
3609 case DISPLAY_ORIENTATION_0:
3610 default:
3611 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3612 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3613 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3614 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3615 naturalPhysicalLeft = mViewport.physicalLeft;
3616 naturalPhysicalTop = mViewport.physicalTop;
3617 naturalDeviceWidth = mViewport.deviceWidth;
3618 naturalDeviceHeight = mViewport.deviceHeight;
3619 break;
3620 }
3621
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003622 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3623 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3624 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3625 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3626 }
3627
Michael Wright358bcc72018-08-21 04:01:07 +01003628 mPhysicalWidth = naturalPhysicalWidth;
3629 mPhysicalHeight = naturalPhysicalHeight;
3630 mPhysicalLeft = naturalPhysicalLeft;
3631 mPhysicalTop = naturalPhysicalTop;
3632
Michael Wrightd02c5b62014-02-10 15:10:22 -08003633 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3634 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3635 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3636 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3637
3638 mSurfaceOrientation = mParameters.orientationAware ?
3639 mViewport.orientation : DISPLAY_ORIENTATION_0;
3640 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003641 mPhysicalWidth = rawWidth;
3642 mPhysicalHeight = rawHeight;
3643 mPhysicalLeft = 0;
3644 mPhysicalTop = 0;
3645
Michael Wrightd02c5b62014-02-10 15:10:22 -08003646 mSurfaceWidth = rawWidth;
3647 mSurfaceHeight = rawHeight;
3648 mSurfaceLeft = 0;
3649 mSurfaceTop = 0;
3650 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3651 }
3652 }
3653
3654 // If moving between pointer modes, need to reset some state.
3655 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3656 if (deviceModeChanged) {
3657 mOrientedRanges.clear();
3658 }
3659
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003660 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003661 if (mDeviceMode == DEVICE_MODE_POINTER ||
3662 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003663 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3665 }
3666 } else {
3667 mPointerController.clear();
3668 }
3669
3670 if (viewportChanged || deviceModeChanged) {
3671 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3672 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003673 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003674 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3675
3676 // Configure X and Y factors.
3677 mXScale = float(mSurfaceWidth) / rawWidth;
3678 mYScale = float(mSurfaceHeight) / rawHeight;
3679 mXTranslate = -mSurfaceLeft;
3680 mYTranslate = -mSurfaceTop;
3681 mXPrecision = 1.0f / mXScale;
3682 mYPrecision = 1.0f / mYScale;
3683
3684 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3685 mOrientedRanges.x.source = mSource;
3686 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3687 mOrientedRanges.y.source = mSource;
3688
3689 configureVirtualKeys();
3690
3691 // Scale factor for terms that are not oriented in a particular axis.
3692 // If the pixels are square then xScale == yScale otherwise we fake it
3693 // by choosing an average.
3694 mGeometricScale = avg(mXScale, mYScale);
3695
3696 // Size of diagonal axis.
3697 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3698
3699 // Size factors.
3700 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3701 if (mRawPointerAxes.touchMajor.valid
3702 && mRawPointerAxes.touchMajor.maxValue != 0) {
3703 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3704 } else if (mRawPointerAxes.toolMajor.valid
3705 && mRawPointerAxes.toolMajor.maxValue != 0) {
3706 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3707 } else {
3708 mSizeScale = 0.0f;
3709 }
3710
3711 mOrientedRanges.haveTouchSize = true;
3712 mOrientedRanges.haveToolSize = true;
3713 mOrientedRanges.haveSize = true;
3714
3715 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3716 mOrientedRanges.touchMajor.source = mSource;
3717 mOrientedRanges.touchMajor.min = 0;
3718 mOrientedRanges.touchMajor.max = diagonalSize;
3719 mOrientedRanges.touchMajor.flat = 0;
3720 mOrientedRanges.touchMajor.fuzz = 0;
3721 mOrientedRanges.touchMajor.resolution = 0;
3722
3723 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3724 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3725
3726 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3727 mOrientedRanges.toolMajor.source = mSource;
3728 mOrientedRanges.toolMajor.min = 0;
3729 mOrientedRanges.toolMajor.max = diagonalSize;
3730 mOrientedRanges.toolMajor.flat = 0;
3731 mOrientedRanges.toolMajor.fuzz = 0;
3732 mOrientedRanges.toolMajor.resolution = 0;
3733
3734 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3735 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3736
3737 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3738 mOrientedRanges.size.source = mSource;
3739 mOrientedRanges.size.min = 0;
3740 mOrientedRanges.size.max = 1.0;
3741 mOrientedRanges.size.flat = 0;
3742 mOrientedRanges.size.fuzz = 0;
3743 mOrientedRanges.size.resolution = 0;
3744 } else {
3745 mSizeScale = 0.0f;
3746 }
3747
3748 // Pressure factors.
3749 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003750 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003751 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3752 || mCalibration.pressureCalibration
3753 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3754 if (mCalibration.havePressureScale) {
3755 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003756 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003757 } else if (mRawPointerAxes.pressure.valid
3758 && mRawPointerAxes.pressure.maxValue != 0) {
3759 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3760 }
3761 }
3762
3763 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3764 mOrientedRanges.pressure.source = mSource;
3765 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003766 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003767 mOrientedRanges.pressure.flat = 0;
3768 mOrientedRanges.pressure.fuzz = 0;
3769 mOrientedRanges.pressure.resolution = 0;
3770
3771 // Tilt
3772 mTiltXCenter = 0;
3773 mTiltXScale = 0;
3774 mTiltYCenter = 0;
3775 mTiltYScale = 0;
3776 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3777 if (mHaveTilt) {
3778 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3779 mRawPointerAxes.tiltX.maxValue);
3780 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3781 mRawPointerAxes.tiltY.maxValue);
3782 mTiltXScale = M_PI / 180;
3783 mTiltYScale = M_PI / 180;
3784
3785 mOrientedRanges.haveTilt = true;
3786
3787 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3788 mOrientedRanges.tilt.source = mSource;
3789 mOrientedRanges.tilt.min = 0;
3790 mOrientedRanges.tilt.max = M_PI_2;
3791 mOrientedRanges.tilt.flat = 0;
3792 mOrientedRanges.tilt.fuzz = 0;
3793 mOrientedRanges.tilt.resolution = 0;
3794 }
3795
3796 // Orientation
3797 mOrientationScale = 0;
3798 if (mHaveTilt) {
3799 mOrientedRanges.haveOrientation = true;
3800
3801 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3802 mOrientedRanges.orientation.source = mSource;
3803 mOrientedRanges.orientation.min = -M_PI;
3804 mOrientedRanges.orientation.max = M_PI;
3805 mOrientedRanges.orientation.flat = 0;
3806 mOrientedRanges.orientation.fuzz = 0;
3807 mOrientedRanges.orientation.resolution = 0;
3808 } else if (mCalibration.orientationCalibration !=
3809 Calibration::ORIENTATION_CALIBRATION_NONE) {
3810 if (mCalibration.orientationCalibration
3811 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3812 if (mRawPointerAxes.orientation.valid) {
3813 if (mRawPointerAxes.orientation.maxValue > 0) {
3814 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3815 } else if (mRawPointerAxes.orientation.minValue < 0) {
3816 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3817 } else {
3818 mOrientationScale = 0;
3819 }
3820 }
3821 }
3822
3823 mOrientedRanges.haveOrientation = true;
3824
3825 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3826 mOrientedRanges.orientation.source = mSource;
3827 mOrientedRanges.orientation.min = -M_PI_2;
3828 mOrientedRanges.orientation.max = M_PI_2;
3829 mOrientedRanges.orientation.flat = 0;
3830 mOrientedRanges.orientation.fuzz = 0;
3831 mOrientedRanges.orientation.resolution = 0;
3832 }
3833
3834 // Distance
3835 mDistanceScale = 0;
3836 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3837 if (mCalibration.distanceCalibration
3838 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3839 if (mCalibration.haveDistanceScale) {
3840 mDistanceScale = mCalibration.distanceScale;
3841 } else {
3842 mDistanceScale = 1.0f;
3843 }
3844 }
3845
3846 mOrientedRanges.haveDistance = true;
3847
3848 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3849 mOrientedRanges.distance.source = mSource;
3850 mOrientedRanges.distance.min =
3851 mRawPointerAxes.distance.minValue * mDistanceScale;
3852 mOrientedRanges.distance.max =
3853 mRawPointerAxes.distance.maxValue * mDistanceScale;
3854 mOrientedRanges.distance.flat = 0;
3855 mOrientedRanges.distance.fuzz =
3856 mRawPointerAxes.distance.fuzz * mDistanceScale;
3857 mOrientedRanges.distance.resolution = 0;
3858 }
3859
3860 // Compute oriented precision, scales and ranges.
3861 // Note that the maximum value reported is an inclusive maximum value so it is one
3862 // unit less than the total width or height of surface.
3863 switch (mSurfaceOrientation) {
3864 case DISPLAY_ORIENTATION_90:
3865 case DISPLAY_ORIENTATION_270:
3866 mOrientedXPrecision = mYPrecision;
3867 mOrientedYPrecision = mXPrecision;
3868
3869 mOrientedRanges.x.min = mYTranslate;
3870 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3871 mOrientedRanges.x.flat = 0;
3872 mOrientedRanges.x.fuzz = 0;
3873 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3874
3875 mOrientedRanges.y.min = mXTranslate;
3876 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3877 mOrientedRanges.y.flat = 0;
3878 mOrientedRanges.y.fuzz = 0;
3879 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3880 break;
3881
3882 default:
3883 mOrientedXPrecision = mXPrecision;
3884 mOrientedYPrecision = mYPrecision;
3885
3886 mOrientedRanges.x.min = mXTranslate;
3887 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3888 mOrientedRanges.x.flat = 0;
3889 mOrientedRanges.x.fuzz = 0;
3890 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3891
3892 mOrientedRanges.y.min = mYTranslate;
3893 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3894 mOrientedRanges.y.flat = 0;
3895 mOrientedRanges.y.fuzz = 0;
3896 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3897 break;
3898 }
3899
Jason Gerecke71b16e82014-03-10 09:47:59 -07003900 // Location
3901 updateAffineTransformation();
3902
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903 if (mDeviceMode == DEVICE_MODE_POINTER) {
3904 // Compute pointer gesture detection parameters.
3905 float rawDiagonal = hypotf(rawWidth, rawHeight);
3906 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3907
3908 // Scale movements such that one whole swipe of the touch pad covers a
3909 // given area relative to the diagonal size of the display when no acceleration
3910 // is applied.
3911 // Assume that the touch pad has a square aspect ratio such that movements in
3912 // X and Y of the same number of raw units cover the same physical distance.
3913 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3914 * displayDiagonal / rawDiagonal;
3915 mPointerYMovementScale = mPointerXMovementScale;
3916
3917 // Scale zooms to cover a smaller range of the display than movements do.
3918 // This value determines the area around the pointer that is affected by freeform
3919 // pointer gestures.
3920 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3921 * displayDiagonal / rawDiagonal;
3922 mPointerYZoomScale = mPointerXZoomScale;
3923
3924 // Max width between pointers to detect a swipe gesture is more than some fraction
3925 // of the diagonal axis of the touch pad. Touches that are wider than this are
3926 // translated into freeform gestures.
3927 mPointerGestureMaxSwipeWidth =
3928 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3929
3930 // Abort current pointer usages because the state has changed.
3931 abortPointerUsage(when, 0 /*policyFlags*/);
3932 }
3933
3934 // Inform the dispatcher about the changes.
3935 *outResetNeeded = true;
3936 bumpGeneration();
3937 }
3938}
3939
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003940void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003941 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003942 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3943 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3944 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3945 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003946 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3947 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3948 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3949 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003950 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003951}
3952
3953void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003954 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3956
3957 mVirtualKeys.clear();
3958
3959 if (virtualKeyDefinitions.size() == 0) {
3960 return;
3961 }
3962
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3964 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003965 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3966 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003967
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003968 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3969 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003970
3971 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3972 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003973 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003974 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003975 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3976 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3978 virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003979 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003980 }
3981
3982 virtualKey.keyCode = keyCode;
3983 virtualKey.flags = flags;
3984
3985 // convert the key definition's display coordinates into touch coordinates for a hit box
3986 int32_t halfWidth = virtualKeyDefinition.width / 2;
3987 int32_t halfHeight = virtualKeyDefinition.height / 2;
3988
3989 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3990 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3991 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3992 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3993 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3994 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3995 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3996 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003997 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003998 }
3999}
4000
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004001void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004002 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004003 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004004
4005 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004006 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004007 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08004008 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4009 i, virtualKey.scanCode, virtualKey.keyCode,
4010 virtualKey.hitLeft, virtualKey.hitRight,
4011 virtualKey.hitTop, virtualKey.hitBottom);
4012 }
4013 }
4014}
4015
4016void TouchInputMapper::parseCalibration() {
4017 const PropertyMap& in = getDevice()->getConfiguration();
4018 Calibration& out = mCalibration;
4019
4020 // Size
4021 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4022 String8 sizeCalibrationString;
4023 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4024 if (sizeCalibrationString == "none") {
4025 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4026 } else if (sizeCalibrationString == "geometric") {
4027 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4028 } else if (sizeCalibrationString == "diameter") {
4029 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4030 } else if (sizeCalibrationString == "box") {
4031 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4032 } else if (sizeCalibrationString == "area") {
4033 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4034 } else if (sizeCalibrationString != "default") {
4035 ALOGW("Invalid value for touch.size.calibration: '%s'",
4036 sizeCalibrationString.string());
4037 }
4038 }
4039
4040 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4041 out.sizeScale);
4042 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4043 out.sizeBias);
4044 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4045 out.sizeIsSummed);
4046
4047 // Pressure
4048 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4049 String8 pressureCalibrationString;
4050 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4051 if (pressureCalibrationString == "none") {
4052 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4053 } else if (pressureCalibrationString == "physical") {
4054 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4055 } else if (pressureCalibrationString == "amplitude") {
4056 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4057 } else if (pressureCalibrationString != "default") {
4058 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4059 pressureCalibrationString.string());
4060 }
4061 }
4062
4063 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4064 out.pressureScale);
4065
4066 // Orientation
4067 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4068 String8 orientationCalibrationString;
4069 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4070 if (orientationCalibrationString == "none") {
4071 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4072 } else if (orientationCalibrationString == "interpolated") {
4073 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4074 } else if (orientationCalibrationString == "vector") {
4075 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4076 } else if (orientationCalibrationString != "default") {
4077 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4078 orientationCalibrationString.string());
4079 }
4080 }
4081
4082 // Distance
4083 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4084 String8 distanceCalibrationString;
4085 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4086 if (distanceCalibrationString == "none") {
4087 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4088 } else if (distanceCalibrationString == "scaled") {
4089 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4090 } else if (distanceCalibrationString != "default") {
4091 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4092 distanceCalibrationString.string());
4093 }
4094 }
4095
4096 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4097 out.distanceScale);
4098
4099 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4100 String8 coverageCalibrationString;
4101 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4102 if (coverageCalibrationString == "none") {
4103 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4104 } else if (coverageCalibrationString == "box") {
4105 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4106 } else if (coverageCalibrationString != "default") {
4107 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4108 coverageCalibrationString.string());
4109 }
4110 }
4111}
4112
4113void TouchInputMapper::resolveCalibration() {
4114 // Size
4115 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4116 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4117 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4118 }
4119 } else {
4120 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4121 }
4122
4123 // Pressure
4124 if (mRawPointerAxes.pressure.valid) {
4125 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4126 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4127 }
4128 } else {
4129 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4130 }
4131
4132 // Orientation
4133 if (mRawPointerAxes.orientation.valid) {
4134 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4135 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4136 }
4137 } else {
4138 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4139 }
4140
4141 // Distance
4142 if (mRawPointerAxes.distance.valid) {
4143 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4144 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4145 }
4146 } else {
4147 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4148 }
4149
4150 // Coverage
4151 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4152 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4153 }
4154}
4155
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156void TouchInputMapper::dumpCalibration(std::string& dump) {
4157 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158
4159 // Size
4160 switch (mCalibration.sizeCalibration) {
4161 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004168 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004169 break;
4170 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004171 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004172 break;
4173 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 break;
4176 default:
4177 ALOG_ASSERT(false);
4178 }
4179
4180 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 mCalibration.sizeScale);
4183 }
4184
4185 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004186 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004187 mCalibration.sizeBias);
4188 }
4189
4190 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004191 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 toString(mCalibration.sizeIsSummed));
4193 }
4194
4195 // Pressure
4196 switch (mCalibration.pressureCalibration) {
4197 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004198 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199 break;
4200 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004201 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004202 break;
4203 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 break;
4206 default:
4207 ALOG_ASSERT(false);
4208 }
4209
4210 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004211 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004212 mCalibration.pressureScale);
4213 }
4214
4215 // Orientation
4216 switch (mCalibration.orientationCalibration) {
4217 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 break;
4220 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 break;
4223 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004224 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 break;
4226 default:
4227 ALOG_ASSERT(false);
4228 }
4229
4230 // Distance
4231 switch (mCalibration.distanceCalibration) {
4232 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004233 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 break;
4235 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004236 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004237 break;
4238 default:
4239 ALOG_ASSERT(false);
4240 }
4241
4242 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244 mCalibration.distanceScale);
4245 }
4246
4247 switch (mCalibration.coverageCalibration) {
4248 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004249 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 break;
4251 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004252 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004253 break;
4254 default:
4255 ALOG_ASSERT(false);
4256 }
4257}
4258
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004259void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4260 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004261
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004262 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4263 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4264 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4265 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4266 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4267 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004268}
4269
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004270void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004271 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4272 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004273}
4274
Michael Wrightd02c5b62014-02-10 15:10:22 -08004275void TouchInputMapper::reset(nsecs_t when) {
4276 mCursorButtonAccumulator.reset(getDevice());
4277 mCursorScrollAccumulator.reset(getDevice());
4278 mTouchButtonAccumulator.reset(getDevice());
4279
4280 mPointerVelocityControl.reset();
4281 mWheelXVelocityControl.reset();
4282 mWheelYVelocityControl.reset();
4283
Michael Wright842500e2015-03-13 17:32:02 -07004284 mRawStatesPending.clear();
4285 mCurrentRawState.clear();
4286 mCurrentCookedState.clear();
4287 mLastRawState.clear();
4288 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004289 mPointerUsage = POINTER_USAGE_NONE;
4290 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004291 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004292 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 mDownTime = 0;
4294
4295 mCurrentVirtualKey.down = false;
4296
4297 mPointerGesture.reset();
4298 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004299 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004300
Yi Kong9b14ac62018-07-17 13:48:38 -07004301 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4303 mPointerController->clearSpots();
4304 }
4305
4306 InputMapper::reset(when);
4307}
4308
Michael Wright842500e2015-03-13 17:32:02 -07004309void TouchInputMapper::resetExternalStylus() {
4310 mExternalStylusState.clear();
4311 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004312 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004313 mExternalStylusDataPending = false;
4314}
4315
Michael Wright43fd19f2015-04-21 19:02:58 +01004316void TouchInputMapper::clearStylusDataPendingFlags() {
4317 mExternalStylusDataPending = false;
4318 mExternalStylusFusionTimeout = LLONG_MAX;
4319}
4320
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004321void TouchInputMapper::reportEventForStatistics(nsecs_t evdevTime) {
4322 nsecs_t now = systemTime(CLOCK_MONOTONIC);
4323 nsecs_t latency = now - evdevTime;
4324 mStatistics.addValue(nanoseconds_to_microseconds(latency));
4325 nsecs_t timeSinceLastReport = now - mStatistics.lastReportTime;
4326 if (timeSinceLastReport > STATISTICS_REPORT_FREQUENCY) {
4327 android::util::stats_write(android::util::TOUCH_EVENT_REPORTED,
Siarhei Vishniakou05247bb2019-03-22 17:11:21 -07004328 mStatistics.min, mStatistics.max,
4329 mStatistics.mean(), mStatistics.stdev(), mStatistics.count);
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004330 mStatistics.reset(now);
4331 }
4332}
4333
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334void TouchInputMapper::process(const RawEvent* rawEvent) {
4335 mCursorButtonAccumulator.process(rawEvent);
4336 mCursorScrollAccumulator.process(rawEvent);
4337 mTouchButtonAccumulator.process(rawEvent);
4338
4339 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -08004340 reportEventForStatistics(rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004341 sync(rawEvent->when);
4342 }
4343}
4344
4345void TouchInputMapper::sync(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004346 const RawState* last = mRawStatesPending.empty() ?
4347 &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004348
4349 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004350 mRawStatesPending.emplace_back();
4351
4352 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004353 next->clear();
4354 next->when = when;
4355
Michael Wrightd02c5b62014-02-10 15:10:22 -08004356 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004357 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004358 | mCursorButtonAccumulator.getButtonState();
4359
Michael Wright842500e2015-03-13 17:32:02 -07004360 // Sync scroll
4361 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4362 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004363 mCursorScrollAccumulator.finishSync();
4364
Michael Wright842500e2015-03-13 17:32:02 -07004365 // Sync touch
4366 syncTouch(when, next);
4367
4368 // Assign pointer ids.
4369 if (!mHavePointerIds) {
4370 assignPointerIds(last, next);
4371 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004372
4373#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004374 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4375 "hovering ids 0x%08x -> 0x%08x",
4376 last->rawPointerData.pointerCount,
4377 next->rawPointerData.pointerCount,
4378 last->rawPointerData.touchingIdBits.value,
4379 next->rawPointerData.touchingIdBits.value,
4380 last->rawPointerData.hoveringIdBits.value,
4381 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004382#endif
4383
Michael Wright842500e2015-03-13 17:32:02 -07004384 processRawTouches(false /*timeout*/);
4385}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004386
Michael Wright842500e2015-03-13 17:32:02 -07004387void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004388 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4389 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004390 mCurrentRawState.clear();
4391 mRawStatesPending.clear();
4392 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004393 }
4394
Michael Wright842500e2015-03-13 17:32:02 -07004395 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4396 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4397 // touching the current state will only observe the events that have been dispatched to the
4398 // rest of the pipeline.
4399 const size_t N = mRawStatesPending.size();
4400 size_t count;
4401 for(count = 0; count < N; count++) {
4402 const RawState& next = mRawStatesPending[count];
4403
4404 // A failure to assign the stylus id means that we're waiting on stylus data
4405 // and so should defer the rest of the pipeline.
4406 if (assignExternalStylusId(next, timeout)) {
4407 break;
4408 }
4409
4410 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004411 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004412 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004413 if (mCurrentRawState.when < mLastRawState.when) {
4414 mCurrentRawState.when = mLastRawState.when;
4415 }
Michael Wright842500e2015-03-13 17:32:02 -07004416 cookAndDispatch(mCurrentRawState.when);
4417 }
4418 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004419 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004420 }
4421
Michael Wright842500e2015-03-13 17:32:02 -07004422 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004423 if (timeout) {
4424 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4425 clearStylusDataPendingFlags();
4426 mCurrentRawState.copyFrom(mLastRawState);
4427#if DEBUG_STYLUS_FUSION
4428 ALOGD("Timeout expired, synthesizing event with new stylus data");
4429#endif
4430 cookAndDispatch(when);
4431 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4432 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4433 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4434 }
Michael Wright842500e2015-03-13 17:32:02 -07004435 }
4436}
4437
4438void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4439 // Always start with a clean state.
4440 mCurrentCookedState.clear();
4441
4442 // Apply stylus buttons to current raw state.
4443 applyExternalStylusButtonState(when);
4444
4445 // Handle policy on initial down or hover events.
4446 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4447 && mCurrentRawState.rawPointerData.pointerCount != 0;
4448
4449 uint32_t policyFlags = 0;
4450 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4451 if (initialDown || buttonsPressed) {
4452 // If this is a touch screen, hide the pointer on an initial down.
4453 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4454 getContext()->fadePointer();
4455 }
4456
4457 if (mParameters.wake) {
4458 policyFlags |= POLICY_FLAG_WAKE;
4459 }
4460 }
4461
4462 // Consume raw off-screen touches before cooking pointer data.
4463 // If touches are consumed, subsequent code will not receive any pointer data.
4464 if (consumeRawTouches(when, policyFlags)) {
4465 mCurrentRawState.rawPointerData.clear();
4466 }
4467
4468 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4469 // with cooked pointer data that has the same ids and indices as the raw data.
4470 // The following code can use either the raw or cooked data, as needed.
4471 cookPointerData();
4472
4473 // Apply stylus pressure to current cooked state.
4474 applyExternalStylusTouchState(when);
4475
4476 // Synthesize key down from raw buttons if needed.
4477 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004478 mViewport.displayId, policyFlags,
4479 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004480
4481 // Dispatch the touches either directly or by translation through a pointer on screen.
4482 if (mDeviceMode == DEVICE_MODE_POINTER) {
4483 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4484 !idBits.isEmpty(); ) {
4485 uint32_t id = idBits.clearFirstMarkedBit();
4486 const RawPointerData::Pointer& pointer =
4487 mCurrentRawState.rawPointerData.pointerForId(id);
4488 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4489 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4490 mCurrentCookedState.stylusIdBits.markBit(id);
4491 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4492 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4493 mCurrentCookedState.fingerIdBits.markBit(id);
4494 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4495 mCurrentCookedState.mouseIdBits.markBit(id);
4496 }
4497 }
4498 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4499 !idBits.isEmpty(); ) {
4500 uint32_t id = idBits.clearFirstMarkedBit();
4501 const RawPointerData::Pointer& pointer =
4502 mCurrentRawState.rawPointerData.pointerForId(id);
4503 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4504 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4505 mCurrentCookedState.stylusIdBits.markBit(id);
4506 }
4507 }
4508
4509 // Stylus takes precedence over all tools, then mouse, then finger.
4510 PointerUsage pointerUsage = mPointerUsage;
4511 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4512 mCurrentCookedState.mouseIdBits.clear();
4513 mCurrentCookedState.fingerIdBits.clear();
4514 pointerUsage = POINTER_USAGE_STYLUS;
4515 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4516 mCurrentCookedState.fingerIdBits.clear();
4517 pointerUsage = POINTER_USAGE_MOUSE;
4518 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4519 isPointerDown(mCurrentRawState.buttonState)) {
4520 pointerUsage = POINTER_USAGE_GESTURES;
4521 }
4522
4523 dispatchPointerUsage(when, policyFlags, pointerUsage);
4524 } else {
4525 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004526 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004527 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4528 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4529
4530 mPointerController->setButtonState(mCurrentRawState.buttonState);
4531 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4532 mCurrentCookedState.cookedPointerData.idToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08004533 mCurrentCookedState.cookedPointerData.touchingIdBits,
4534 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004535 }
4536
Michael Wright8e812822015-06-22 16:18:21 +01004537 if (!mCurrentMotionAborted) {
4538 dispatchButtonRelease(when, policyFlags);
4539 dispatchHoverExit(when, policyFlags);
4540 dispatchTouches(when, policyFlags);
4541 dispatchHoverEnterAndMove(when, policyFlags);
4542 dispatchButtonPress(when, policyFlags);
4543 }
4544
4545 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4546 mCurrentMotionAborted = false;
4547 }
Michael Wright842500e2015-03-13 17:32:02 -07004548 }
4549
4550 // Synthesize key up from raw buttons if needed.
4551 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004552 mViewport.displayId, policyFlags,
4553 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004554
4555 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004556 mCurrentRawState.rawVScroll = 0;
4557 mCurrentRawState.rawHScroll = 0;
4558
4559 // Copy current touch to last touch in preparation for the next cycle.
4560 mLastRawState.copyFrom(mCurrentRawState);
4561 mLastCookedState.copyFrom(mCurrentCookedState);
4562}
4563
4564void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004565 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004566 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4567 }
4568}
4569
4570void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004571 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4572 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004573
Michael Wright53dca3a2015-04-23 17:39:53 +01004574 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4575 float pressure = mExternalStylusState.pressure;
4576 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4577 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4578 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4579 }
4580 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4581 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4582
4583 PointerProperties& properties =
4584 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004585 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4586 properties.toolType = mExternalStylusState.toolType;
4587 }
4588 }
4589}
4590
4591bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4592 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4593 return false;
4594 }
4595
4596 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4597 && state.rawPointerData.pointerCount != 0;
4598 if (initialDown) {
4599 if (mExternalStylusState.pressure != 0.0f) {
4600#if DEBUG_STYLUS_FUSION
4601 ALOGD("Have both stylus and touch data, beginning fusion");
4602#endif
4603 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4604 } else if (timeout) {
4605#if DEBUG_STYLUS_FUSION
4606 ALOGD("Timeout expired, assuming touch is not a stylus.");
4607#endif
4608 resetExternalStylus();
4609 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004610 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4611 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004612 }
4613#if DEBUG_STYLUS_FUSION
4614 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004615 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004616#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004617 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004618 return true;
4619 }
4620 }
4621
4622 // Check if the stylus pointer has gone up.
4623 if (mExternalStylusId != -1 &&
4624 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4625#if DEBUG_STYLUS_FUSION
4626 ALOGD("Stylus pointer is going up");
4627#endif
4628 mExternalStylusId = -1;
4629 }
4630
4631 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004632}
4633
4634void TouchInputMapper::timeoutExpired(nsecs_t when) {
4635 if (mDeviceMode == DEVICE_MODE_POINTER) {
4636 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4637 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4638 }
Michael Wright842500e2015-03-13 17:32:02 -07004639 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004640 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004641 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004642 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4643 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004644 }
4645 }
4646}
4647
4648void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004649 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004650 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004651 // We're either in the middle of a fused stream of data or we're waiting on data before
4652 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4653 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004654 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004655 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004656 }
4657}
4658
4659bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4660 // Check for release of a virtual key.
4661 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004662 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 // Pointer went up while virtual key was down.
4664 mCurrentVirtualKey.down = false;
4665 if (!mCurrentVirtualKey.ignored) {
4666#if DEBUG_VIRTUAL_KEYS
4667 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4668 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4669#endif
4670 dispatchVirtualKey(when, policyFlags,
4671 AKEY_EVENT_ACTION_UP,
4672 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4673 }
4674 return true;
4675 }
4676
Michael Wright842500e2015-03-13 17:32:02 -07004677 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4678 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4679 const RawPointerData::Pointer& pointer =
4680 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004681 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4682 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4683 // Pointer is still within the space of the virtual key.
4684 return true;
4685 }
4686 }
4687
4688 // Pointer left virtual key area or another pointer also went down.
4689 // Send key cancellation but do not consume the touch yet.
4690 // This is useful when the user swipes through from the virtual key area
4691 // into the main display surface.
4692 mCurrentVirtualKey.down = false;
4693 if (!mCurrentVirtualKey.ignored) {
4694#if DEBUG_VIRTUAL_KEYS
4695 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4696 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4697#endif
4698 dispatchVirtualKey(when, policyFlags,
4699 AKEY_EVENT_ACTION_UP,
4700 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4701 | AKEY_EVENT_FLAG_CANCELED);
4702 }
4703 }
4704
Michael Wright842500e2015-03-13 17:32:02 -07004705 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4706 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004707 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004708 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4709 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4711 // If exactly one pointer went down, check for virtual key hit.
4712 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004713 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004714 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4715 if (virtualKey) {
4716 mCurrentVirtualKey.down = true;
4717 mCurrentVirtualKey.downTime = when;
4718 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4719 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4720 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4721 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4722
4723 if (!mCurrentVirtualKey.ignored) {
4724#if DEBUG_VIRTUAL_KEYS
4725 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4726 mCurrentVirtualKey.keyCode,
4727 mCurrentVirtualKey.scanCode);
4728#endif
4729 dispatchVirtualKey(when, policyFlags,
4730 AKEY_EVENT_ACTION_DOWN,
4731 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4732 }
4733 }
4734 }
4735 return true;
4736 }
4737 }
4738
4739 // Disable all virtual key touches that happen within a short time interval of the
4740 // most recent touch within the screen area. The idea is to filter out stray
4741 // virtual key presses when interacting with the touch screen.
4742 //
4743 // Problems we're trying to solve:
4744 //
4745 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4746 // virtual key area that is implemented by a separate touch panel and accidentally
4747 // triggers a virtual key.
4748 //
4749 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4750 // area and accidentally triggers a virtual key. This often happens when virtual keys
4751 // are layed out below the screen near to where the on screen keyboard's space bar
4752 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004753 if (mConfig.virtualKeyQuietTime > 0 &&
4754 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4756 }
4757 return false;
4758}
4759
4760void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4761 int32_t keyEventAction, int32_t keyEventFlags) {
4762 int32_t keyCode = mCurrentVirtualKey.keyCode;
4763 int32_t scanCode = mCurrentVirtualKey.scanCode;
4764 nsecs_t downTime = mCurrentVirtualKey.downTime;
4765 int32_t metaState = mContext->getGlobalMetaState();
4766 policyFlags |= POLICY_FLAG_VIRTUAL;
4767
Prabir Pradhan42611e02018-11-27 14:04:02 -08004768 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4769 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004770 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004771 getListener()->notifyKey(&args);
4772}
4773
Michael Wright8e812822015-06-22 16:18:21 +01004774void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4775 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4776 if (!currentIdBits.isEmpty()) {
4777 int32_t metaState = getContext()->getGlobalMetaState();
4778 int32_t buttonState = mCurrentCookedState.buttonState;
4779 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4780 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4781 mCurrentCookedState.cookedPointerData.pointerProperties,
4782 mCurrentCookedState.cookedPointerData.pointerCoords,
4783 mCurrentCookedState.cookedPointerData.idToIndex,
4784 currentIdBits, -1,
4785 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4786 mCurrentMotionAborted = true;
4787 }
4788}
4789
Michael Wrightd02c5b62014-02-10 15:10:22 -08004790void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004791 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4792 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004794 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004795
4796 if (currentIdBits == lastIdBits) {
4797 if (!currentIdBits.isEmpty()) {
4798 // No pointer id changes so this is a move event.
4799 // The listener takes care of batching moves so we don't have to deal with that here.
4800 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004801 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004802 AMOTION_EVENT_EDGE_FLAG_NONE,
Michael Wright842500e2015-03-13 17:32:02 -07004803 mCurrentCookedState.cookedPointerData.pointerProperties,
4804 mCurrentCookedState.cookedPointerData.pointerCoords,
4805 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 currentIdBits, -1,
4807 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4808 }
4809 } else {
4810 // There may be pointers going up and pointers going down and pointers moving
4811 // all at the same time.
4812 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4813 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4814 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4815 BitSet32 dispatchedIdBits(lastIdBits.value);
4816
4817 // Update last coordinates of pointers that have moved so that we observe the new
4818 // pointer positions at the same time as other pointers that have just gone up.
4819 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004820 mCurrentCookedState.cookedPointerData.pointerProperties,
4821 mCurrentCookedState.cookedPointerData.pointerCoords,
4822 mCurrentCookedState.cookedPointerData.idToIndex,
4823 mLastCookedState.cookedPointerData.pointerProperties,
4824 mLastCookedState.cookedPointerData.pointerCoords,
4825 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004827 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004828 moveNeeded = true;
4829 }
4830
4831 // Dispatch pointer up events.
4832 while (!upIdBits.isEmpty()) {
4833 uint32_t upId = upIdBits.clearFirstMarkedBit();
4834
4835 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004836 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004837 mLastCookedState.cookedPointerData.pointerProperties,
4838 mLastCookedState.cookedPointerData.pointerCoords,
4839 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004840 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004841 dispatchedIdBits.clearBit(upId);
4842 }
4843
4844 // Dispatch move events if any of the remaining pointers moved from their old locations.
4845 // Although applications receive new locations as part of individual pointer up
4846 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004847 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004848 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4849 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004850 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004851 mCurrentCookedState.cookedPointerData.pointerProperties,
4852 mCurrentCookedState.cookedPointerData.pointerCoords,
4853 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004854 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 }
4856
4857 // Dispatch pointer down events using the new pointer locations.
4858 while (!downIdBits.isEmpty()) {
4859 uint32_t downId = downIdBits.clearFirstMarkedBit();
4860 dispatchedIdBits.markBit(downId);
4861
4862 if (dispatchedIdBits.count() == 1) {
4863 // First pointer is going down. Set down time.
4864 mDownTime = when;
4865 }
4866
4867 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004868 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004869 mCurrentCookedState.cookedPointerData.pointerProperties,
4870 mCurrentCookedState.cookedPointerData.pointerCoords,
4871 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004872 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874 }
4875}
4876
4877void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4878 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004879 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4880 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004881 int32_t metaState = getContext()->getGlobalMetaState();
4882 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004883 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004884 mLastCookedState.cookedPointerData.pointerProperties,
4885 mLastCookedState.cookedPointerData.pointerCoords,
4886 mLastCookedState.cookedPointerData.idToIndex,
4887 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004888 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4889 mSentHoverEnter = false;
4890 }
4891}
4892
4893void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004894 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4895 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004896 int32_t metaState = getContext()->getGlobalMetaState();
4897 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004898 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004899 0, 0, metaState, mCurrentRawState.buttonState, 0,
Michael Wright842500e2015-03-13 17:32:02 -07004900 mCurrentCookedState.cookedPointerData.pointerProperties,
4901 mCurrentCookedState.cookedPointerData.pointerCoords,
4902 mCurrentCookedState.cookedPointerData.idToIndex,
4903 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004904 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4905 mSentHoverEnter = true;
4906 }
4907
4908 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004909 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004910 mCurrentRawState.buttonState, 0,
4911 mCurrentCookedState.cookedPointerData.pointerProperties,
4912 mCurrentCookedState.cookedPointerData.pointerCoords,
4913 mCurrentCookedState.cookedPointerData.idToIndex,
4914 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4916 }
4917}
4918
Michael Wright7b159c92015-05-14 14:48:03 +01004919void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4920 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4921 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4922 const int32_t metaState = getContext()->getGlobalMetaState();
4923 int32_t buttonState = mLastCookedState.buttonState;
4924 while (!releasedButtons.isEmpty()) {
4925 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4926 buttonState &= ~actionButton;
4927 dispatchMotion(when, policyFlags, mSource,
4928 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4929 0, metaState, buttonState, 0,
4930 mCurrentCookedState.cookedPointerData.pointerProperties,
4931 mCurrentCookedState.cookedPointerData.pointerCoords,
4932 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4933 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4934 }
4935}
4936
4937void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4938 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4939 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4940 const int32_t metaState = getContext()->getGlobalMetaState();
4941 int32_t buttonState = mLastCookedState.buttonState;
4942 while (!pressedButtons.isEmpty()) {
4943 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4944 buttonState |= actionButton;
4945 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4946 0, metaState, buttonState, 0,
4947 mCurrentCookedState.cookedPointerData.pointerProperties,
4948 mCurrentCookedState.cookedPointerData.pointerCoords,
4949 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4950 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4951 }
4952}
4953
4954const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4955 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4956 return cookedPointerData.touchingIdBits;
4957 }
4958 return cookedPointerData.hoveringIdBits;
4959}
4960
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004962 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004963
Michael Wright842500e2015-03-13 17:32:02 -07004964 mCurrentCookedState.cookedPointerData.clear();
4965 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4966 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4967 mCurrentRawState.rawPointerData.hoveringIdBits;
4968 mCurrentCookedState.cookedPointerData.touchingIdBits =
4969 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004970
Michael Wright7b159c92015-05-14 14:48:03 +01004971 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4972 mCurrentCookedState.buttonState = 0;
4973 } else {
4974 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4975 }
4976
Michael Wrightd02c5b62014-02-10 15:10:22 -08004977 // Walk through the the active pointers and map device coordinates onto
4978 // surface coordinates and adjust for display orientation.
4979 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004980 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004981
4982 // Size
4983 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4984 switch (mCalibration.sizeCalibration) {
4985 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4986 case Calibration::SIZE_CALIBRATION_DIAMETER:
4987 case Calibration::SIZE_CALIBRATION_BOX:
4988 case Calibration::SIZE_CALIBRATION_AREA:
4989 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4990 touchMajor = in.touchMajor;
4991 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4992 toolMajor = in.toolMajor;
4993 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4994 size = mRawPointerAxes.touchMinor.valid
4995 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4996 } else if (mRawPointerAxes.touchMajor.valid) {
4997 toolMajor = touchMajor = in.touchMajor;
4998 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4999 ? in.touchMinor : in.touchMajor;
5000 size = mRawPointerAxes.touchMinor.valid
5001 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
5002 } else if (mRawPointerAxes.toolMajor.valid) {
5003 touchMajor = toolMajor = in.toolMajor;
5004 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
5005 ? in.toolMinor : in.toolMajor;
5006 size = mRawPointerAxes.toolMinor.valid
5007 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
5008 } else {
5009 ALOG_ASSERT(false, "No touch or tool axes. "
5010 "Size calibration should have been resolved to NONE.");
5011 touchMajor = 0;
5012 touchMinor = 0;
5013 toolMajor = 0;
5014 toolMinor = 0;
5015 size = 0;
5016 }
5017
5018 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07005019 uint32_t touchingCount =
5020 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005021 if (touchingCount > 1) {
5022 touchMajor /= touchingCount;
5023 touchMinor /= touchingCount;
5024 toolMajor /= touchingCount;
5025 toolMinor /= touchingCount;
5026 size /= touchingCount;
5027 }
5028 }
5029
5030 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
5031 touchMajor *= mGeometricScale;
5032 touchMinor *= mGeometricScale;
5033 toolMajor *= mGeometricScale;
5034 toolMinor *= mGeometricScale;
5035 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5036 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5037 touchMinor = touchMajor;
5038 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5039 toolMinor = toolMajor;
5040 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5041 touchMinor = touchMajor;
5042 toolMinor = toolMajor;
5043 }
5044
5045 mCalibration.applySizeScaleAndBias(&touchMajor);
5046 mCalibration.applySizeScaleAndBias(&touchMinor);
5047 mCalibration.applySizeScaleAndBias(&toolMajor);
5048 mCalibration.applySizeScaleAndBias(&toolMinor);
5049 size *= mSizeScale;
5050 break;
5051 default:
5052 touchMajor = 0;
5053 touchMinor = 0;
5054 toolMajor = 0;
5055 toolMinor = 0;
5056 size = 0;
5057 break;
5058 }
5059
5060 // Pressure
5061 float pressure;
5062 switch (mCalibration.pressureCalibration) {
5063 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5064 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5065 pressure = in.pressure * mPressureScale;
5066 break;
5067 default:
5068 pressure = in.isHovering ? 0 : 1;
5069 break;
5070 }
5071
5072 // Tilt and Orientation
5073 float tilt;
5074 float orientation;
5075 if (mHaveTilt) {
5076 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5077 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5078 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5079 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5080 } else {
5081 tilt = 0;
5082
5083 switch (mCalibration.orientationCalibration) {
5084 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5085 orientation = in.orientation * mOrientationScale;
5086 break;
5087 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5088 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5089 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5090 if (c1 != 0 || c2 != 0) {
5091 orientation = atan2f(c1, c2) * 0.5f;
5092 float confidence = hypotf(c1, c2);
5093 float scale = 1.0f + confidence / 16.0f;
5094 touchMajor *= scale;
5095 touchMinor /= scale;
5096 toolMajor *= scale;
5097 toolMinor /= scale;
5098 } else {
5099 orientation = 0;
5100 }
5101 break;
5102 }
5103 default:
5104 orientation = 0;
5105 }
5106 }
5107
5108 // Distance
5109 float distance;
5110 switch (mCalibration.distanceCalibration) {
5111 case Calibration::DISTANCE_CALIBRATION_SCALED:
5112 distance = in.distance * mDistanceScale;
5113 break;
5114 default:
5115 distance = 0;
5116 }
5117
5118 // Coverage
5119 int32_t rawLeft, rawTop, rawRight, rawBottom;
5120 switch (mCalibration.coverageCalibration) {
5121 case Calibration::COVERAGE_CALIBRATION_BOX:
5122 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5123 rawRight = in.toolMinor & 0x0000ffff;
5124 rawBottom = in.toolMajor & 0x0000ffff;
5125 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5126 break;
5127 default:
5128 rawLeft = rawTop = rawRight = rawBottom = 0;
5129 break;
5130 }
5131
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005132 // Adjust X,Y coords for device calibration
5133 // TODO: Adjust coverage coords?
5134 float xTransformed = in.x, yTransformed = in.y;
5135 mAffineTransform.applyTo(xTransformed, yTransformed);
5136
5137 // Adjust X, Y, and coverage coords for surface orientation.
5138 float x, y;
5139 float left, top, right, bottom;
5140
Michael Wrightd02c5b62014-02-10 15:10:22 -08005141 switch (mSurfaceOrientation) {
5142 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005143 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5144 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005145 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5146 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5147 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5148 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5149 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005150 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005151 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5152 }
5153 break;
5154 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005155 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005156 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005157 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5158 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005159 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5160 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5161 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005162 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005163 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5164 }
5165 break;
5166 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005167 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005168 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005169 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5170 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005171 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5172 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5173 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005174 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005175 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5176 }
5177 break;
5178 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005179 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5180 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5182 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5183 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5184 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5185 break;
5186 }
5187
5188 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005189 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005190 out.clear();
5191 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5192 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5193 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5194 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5195 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5196 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5197 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5198 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5199 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5200 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5201 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5202 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5203 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5204 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5205 } else {
5206 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5207 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5208 }
5209
5210 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005211 PointerProperties& properties =
5212 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005213 uint32_t id = in.id;
5214 properties.clear();
5215 properties.id = id;
5216 properties.toolType = in.toolType;
5217
5218 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005219 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220 }
5221}
5222
5223void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5224 PointerUsage pointerUsage) {
5225 if (pointerUsage != mPointerUsage) {
5226 abortPointerUsage(when, policyFlags);
5227 mPointerUsage = pointerUsage;
5228 }
5229
5230 switch (mPointerUsage) {
5231 case POINTER_USAGE_GESTURES:
5232 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5233 break;
5234 case POINTER_USAGE_STYLUS:
5235 dispatchPointerStylus(when, policyFlags);
5236 break;
5237 case POINTER_USAGE_MOUSE:
5238 dispatchPointerMouse(when, policyFlags);
5239 break;
5240 default:
5241 break;
5242 }
5243}
5244
5245void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5246 switch (mPointerUsage) {
5247 case POINTER_USAGE_GESTURES:
5248 abortPointerGestures(when, policyFlags);
5249 break;
5250 case POINTER_USAGE_STYLUS:
5251 abortPointerStylus(when, policyFlags);
5252 break;
5253 case POINTER_USAGE_MOUSE:
5254 abortPointerMouse(when, policyFlags);
5255 break;
5256 default:
5257 break;
5258 }
5259
5260 mPointerUsage = POINTER_USAGE_NONE;
5261}
5262
5263void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5264 bool isTimeout) {
5265 // Update current gesture coordinates.
5266 bool cancelPreviousGesture, finishPreviousGesture;
5267 bool sendEvents = preparePointerGestures(when,
5268 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5269 if (!sendEvents) {
5270 return;
5271 }
5272 if (finishPreviousGesture) {
5273 cancelPreviousGesture = false;
5274 }
5275
5276 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005277 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5278 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005279 if (finishPreviousGesture || cancelPreviousGesture) {
5280 mPointerController->clearSpots();
5281 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005282
5283 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5284 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5285 mPointerGesture.currentGestureIdToIndex,
Arthur Hung7c645402019-01-25 17:45:42 +08005286 mPointerGesture.currentGestureIdBits,
5287 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005288 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005289 } else {
5290 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5291 }
5292
5293 // Show or hide the pointer if needed.
5294 switch (mPointerGesture.currentGestureMode) {
5295 case PointerGesture::NEUTRAL:
5296 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005297 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5298 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 // Remind the user of where the pointer is after finishing a gesture with spots.
5300 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5301 }
5302 break;
5303 case PointerGesture::TAP:
5304 case PointerGesture::TAP_DRAG:
5305 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5306 case PointerGesture::HOVER:
5307 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005308 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 // Unfade the pointer when the current gesture manipulates the
5310 // area directly under the pointer.
5311 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5312 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005313 case PointerGesture::FREEFORM:
5314 // Fade the pointer when the current gesture manipulates a different
5315 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005316 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5318 } else {
5319 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5320 }
5321 break;
5322 }
5323
5324 // Send events!
5325 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005326 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327
5328 // Update last coordinates of pointers that have moved so that we observe the new
5329 // pointer positions at the same time as other pointers that have just gone up.
5330 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5331 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5332 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5333 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5334 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5335 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5336 bool moveNeeded = false;
5337 if (down && !cancelPreviousGesture && !finishPreviousGesture
5338 && !mPointerGesture.lastGestureIdBits.isEmpty()
5339 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5340 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5341 & mPointerGesture.lastGestureIdBits.value);
5342 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5343 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5344 mPointerGesture.lastGestureProperties,
5345 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5346 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005347 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 moveNeeded = true;
5349 }
5350 }
5351
5352 // Send motion events for all pointers that went up or were canceled.
5353 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5354 if (!dispatchedGestureIdBits.isEmpty()) {
5355 if (cancelPreviousGesture) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005356 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5357 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5358 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5359 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5360 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361
5362 dispatchedGestureIdBits.clear();
5363 } else {
5364 BitSet32 upGestureIdBits;
5365 if (finishPreviousGesture) {
5366 upGestureIdBits = dispatchedGestureIdBits;
5367 } else {
5368 upGestureIdBits.value = dispatchedGestureIdBits.value
5369 & ~mPointerGesture.currentGestureIdBits.value;
5370 }
5371 while (!upGestureIdBits.isEmpty()) {
5372 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5373
5374 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005375 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005376 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5377 mPointerGesture.lastGestureProperties,
5378 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5379 dispatchedGestureIdBits, id,
5380 0, 0, mPointerGesture.downTime);
5381
5382 dispatchedGestureIdBits.clearBit(id);
5383 }
5384 }
5385 }
5386
5387 // Send motion events for all pointers that moved.
5388 if (moveNeeded) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005389 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5390 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5391 mPointerGesture.currentGestureProperties,
5392 mPointerGesture.currentGestureCoords,
5393 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5394 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005395 }
5396
5397 // Send motion events for all pointers that went down.
5398 if (down) {
5399 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5400 & ~dispatchedGestureIdBits.value);
5401 while (!downGestureIdBits.isEmpty()) {
5402 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5403 dispatchedGestureIdBits.markBit(id);
5404
5405 if (dispatchedGestureIdBits.count() == 1) {
5406 mPointerGesture.downTime = when;
5407 }
5408
5409 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005410 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005411 mPointerGesture.currentGestureProperties,
5412 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5413 dispatchedGestureIdBits, id,
5414 0, 0, mPointerGesture.downTime);
5415 }
5416 }
5417
5418 // Send motion events for hover.
5419 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005420 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5421 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5422 mPointerGesture.currentGestureProperties,
5423 mPointerGesture.currentGestureCoords,
5424 mPointerGesture.currentGestureIdToIndex,
5425 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005426 } else if (dispatchedGestureIdBits.isEmpty()
5427 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5428 // Synthesize a hover move event after all pointers go up to indicate that
5429 // the pointer is hovering again even if the user is not currently touching
5430 // the touch pad. This ensures that a view will receive a fresh hover enter
5431 // event after a tap.
5432 float x, y;
5433 mPointerController->getPosition(&x, &y);
5434
5435 PointerProperties pointerProperties;
5436 pointerProperties.clear();
5437 pointerProperties.id = 0;
5438 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5439
5440 PointerCoords pointerCoords;
5441 pointerCoords.clear();
5442 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5443 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5444
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005445 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005446 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5447 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5448 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005449 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
5450 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 getListener()->notifyMotion(&args);
5452 }
5453
5454 // Update state.
5455 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5456 if (!down) {
5457 mPointerGesture.lastGestureIdBits.clear();
5458 } else {
5459 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5460 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5461 uint32_t id = idBits.clearFirstMarkedBit();
5462 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5463 mPointerGesture.lastGestureProperties[index].copyFrom(
5464 mPointerGesture.currentGestureProperties[index]);
5465 mPointerGesture.lastGestureCoords[index].copyFrom(
5466 mPointerGesture.currentGestureCoords[index]);
5467 mPointerGesture.lastGestureIdToIndex[id] = index;
5468 }
5469 }
5470}
5471
5472void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5473 // Cancel previously dispatches pointers.
5474 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5475 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005476 int32_t buttonState = mCurrentRawState.buttonState;
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005477 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5478 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5479 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5480 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5481 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005482 }
5483
5484 // Reset the current pointer gesture.
5485 mPointerGesture.reset();
5486 mPointerVelocityControl.reset();
5487
5488 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005489 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005490 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5491 mPointerController->clearSpots();
5492 }
5493}
5494
5495bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5496 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5497 *outCancelPreviousGesture = false;
5498 *outFinishPreviousGesture = false;
5499
5500 // Handle TAP timeout.
5501 if (isTimeout) {
5502#if DEBUG_GESTURES
5503 ALOGD("Gestures: Processing timeout");
5504#endif
5505
5506 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5507 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5508 // The tap/drag timeout has not yet expired.
5509 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5510 + mConfig.pointerGestureTapDragInterval);
5511 } else {
5512 // The tap is finished.
5513#if DEBUG_GESTURES
5514 ALOGD("Gestures: TAP finished");
5515#endif
5516 *outFinishPreviousGesture = true;
5517
5518 mPointerGesture.activeGestureId = -1;
5519 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5520 mPointerGesture.currentGestureIdBits.clear();
5521
5522 mPointerVelocityControl.reset();
5523 return true;
5524 }
5525 }
5526
5527 // We did not handle this timeout.
5528 return false;
5529 }
5530
Michael Wright842500e2015-03-13 17:32:02 -07005531 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5532 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533
5534 // Update the velocity tracker.
5535 {
5536 VelocityTracker::Position positions[MAX_POINTERS];
5537 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005538 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005540 const RawPointerData::Pointer& pointer =
5541 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005542 positions[count].x = pointer.x * mPointerXMovementScale;
5543 positions[count].y = pointer.y * mPointerYMovementScale;
5544 }
5545 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005546 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 }
5548
5549 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5550 // to NEUTRAL, then we should not generate tap event.
5551 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5552 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5553 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5554 mPointerGesture.resetTap();
5555 }
5556
5557 // Pick a new active touch id if needed.
5558 // Choose an arbitrary pointer that just went down, if there is one.
5559 // Otherwise choose an arbitrary remaining pointer.
5560 // This guarantees we always have an active touch id when there is at least one pointer.
5561 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005562 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5563 int32_t activeTouchId = lastActiveTouchId;
5564 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005565 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005567 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005568 mPointerGesture.firstTouchTime = when;
5569 }
Michael Wright842500e2015-03-13 17:32:02 -07005570 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005571 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005572 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005573 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005574 } else {
5575 activeTouchId = mPointerGesture.activeTouchId = -1;
5576 }
5577 }
5578
5579 // Determine whether we are in quiet time.
5580 bool isQuietTime = false;
5581 if (activeTouchId < 0) {
5582 mPointerGesture.resetQuietTime();
5583 } else {
5584 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5585 if (!isQuietTime) {
5586 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5587 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5588 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5589 && currentFingerCount < 2) {
5590 // Enter quiet time when exiting swipe or freeform state.
5591 // This is to prevent accidentally entering the hover state and flinging the
5592 // pointer when finishing a swipe and there is still one pointer left onscreen.
5593 isQuietTime = true;
5594 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5595 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005596 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005597 // Enter quiet time when releasing the button and there are still two or more
5598 // fingers down. This may indicate that one finger was used to press the button
5599 // but it has not gone up yet.
5600 isQuietTime = true;
5601 }
5602 if (isQuietTime) {
5603 mPointerGesture.quietTime = when;
5604 }
5605 }
5606 }
5607
5608 // Switch states based on button and pointer state.
5609 if (isQuietTime) {
5610 // Case 1: Quiet time. (QUIET)
5611#if DEBUG_GESTURES
5612 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5613 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5614#endif
5615 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5616 *outFinishPreviousGesture = true;
5617 }
5618
5619 mPointerGesture.activeGestureId = -1;
5620 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5621 mPointerGesture.currentGestureIdBits.clear();
5622
5623 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005624 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5626 // The pointer follows the active touch point.
5627 // Emit DOWN, MOVE, UP events at the pointer location.
5628 //
5629 // Only the active touch matters; other fingers are ignored. This policy helps
5630 // to handle the case where the user places a second finger on the touch pad
5631 // to apply the necessary force to depress an integrated button below the surface.
5632 // We don't want the second finger to be delivered to applications.
5633 //
5634 // For this to work well, we need to make sure to track the pointer that is really
5635 // active. If the user first puts one finger down to click then adds another
5636 // finger to drag then the active pointer should switch to the finger that is
5637 // being dragged.
5638#if DEBUG_GESTURES
5639 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5640 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5641#endif
5642 // Reset state when just starting.
5643 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5644 *outFinishPreviousGesture = true;
5645 mPointerGesture.activeGestureId = 0;
5646 }
5647
5648 // Switch pointers if needed.
5649 // Find the fastest pointer and follow it.
5650 if (activeTouchId >= 0 && currentFingerCount > 1) {
5651 int32_t bestId = -1;
5652 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005653 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654 uint32_t id = idBits.clearFirstMarkedBit();
5655 float vx, vy;
5656 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5657 float speed = hypotf(vx, vy);
5658 if (speed > bestSpeed) {
5659 bestId = id;
5660 bestSpeed = speed;
5661 }
5662 }
5663 }
5664 if (bestId >= 0 && bestId != activeTouchId) {
5665 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005666#if DEBUG_GESTURES
5667 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5668 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5669#endif
5670 }
5671 }
5672
Jun Mukaifa1706a2015-12-03 01:14:46 -08005673 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005674 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005675 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005676 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005677 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005678 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005679 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5680 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005681
5682 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5683 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5684
5685 // Move the pointer using a relative motion.
5686 // When using spots, the click will occur at the position of the anchor
5687 // spot and all other spots will move there.
5688 mPointerController->move(deltaX, deltaY);
5689 } else {
5690 mPointerVelocityControl.reset();
5691 }
5692
5693 float x, y;
5694 mPointerController->getPosition(&x, &y);
5695
5696 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5697 mPointerGesture.currentGestureIdBits.clear();
5698 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5699 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5700 mPointerGesture.currentGestureProperties[0].clear();
5701 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5702 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5703 mPointerGesture.currentGestureCoords[0].clear();
5704 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5705 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5706 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5707 } else if (currentFingerCount == 0) {
5708 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5709 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5710 *outFinishPreviousGesture = true;
5711 }
5712
5713 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5714 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5715 bool tapped = false;
5716 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5717 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5718 && lastFingerCount == 1) {
5719 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5720 float x, y;
5721 mPointerController->getPosition(&x, &y);
5722 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5723 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5724#if DEBUG_GESTURES
5725 ALOGD("Gestures: TAP");
5726#endif
5727
5728 mPointerGesture.tapUpTime = when;
5729 getContext()->requestTimeoutAtTime(when
5730 + mConfig.pointerGestureTapDragInterval);
5731
5732 mPointerGesture.activeGestureId = 0;
5733 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5734 mPointerGesture.currentGestureIdBits.clear();
5735 mPointerGesture.currentGestureIdBits.markBit(
5736 mPointerGesture.activeGestureId);
5737 mPointerGesture.currentGestureIdToIndex[
5738 mPointerGesture.activeGestureId] = 0;
5739 mPointerGesture.currentGestureProperties[0].clear();
5740 mPointerGesture.currentGestureProperties[0].id =
5741 mPointerGesture.activeGestureId;
5742 mPointerGesture.currentGestureProperties[0].toolType =
5743 AMOTION_EVENT_TOOL_TYPE_FINGER;
5744 mPointerGesture.currentGestureCoords[0].clear();
5745 mPointerGesture.currentGestureCoords[0].setAxisValue(
5746 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5747 mPointerGesture.currentGestureCoords[0].setAxisValue(
5748 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5749 mPointerGesture.currentGestureCoords[0].setAxisValue(
5750 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5751
5752 tapped = true;
5753 } else {
5754#if DEBUG_GESTURES
5755 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5756 x - mPointerGesture.tapX,
5757 y - mPointerGesture.tapY);
5758#endif
5759 }
5760 } else {
5761#if DEBUG_GESTURES
5762 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5763 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5764 (when - mPointerGesture.tapDownTime) * 0.000001f);
5765 } else {
5766 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5767 }
5768#endif
5769 }
5770 }
5771
5772 mPointerVelocityControl.reset();
5773
5774 if (!tapped) {
5775#if DEBUG_GESTURES
5776 ALOGD("Gestures: NEUTRAL");
5777#endif
5778 mPointerGesture.activeGestureId = -1;
5779 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5780 mPointerGesture.currentGestureIdBits.clear();
5781 }
5782 } else if (currentFingerCount == 1) {
5783 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5784 // The pointer follows the active touch point.
5785 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5786 // When in TAP_DRAG, emit MOVE events at the pointer location.
5787 ALOG_ASSERT(activeTouchId >= 0);
5788
5789 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5790 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5791 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5792 float x, y;
5793 mPointerController->getPosition(&x, &y);
5794 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5795 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5796 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5797 } else {
5798#if DEBUG_GESTURES
5799 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5800 x - mPointerGesture.tapX,
5801 y - mPointerGesture.tapY);
5802#endif
5803 }
5804 } else {
5805#if DEBUG_GESTURES
5806 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5807 (when - mPointerGesture.tapUpTime) * 0.000001f);
5808#endif
5809 }
5810 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5811 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5812 }
5813
Jun Mukaifa1706a2015-12-03 01:14:46 -08005814 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005815 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005816 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005817 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005818 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005819 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005820 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5821 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005822
5823 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5824 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5825
5826 // Move the pointer using a relative motion.
5827 // When using spots, the hover or drag will occur at the position of the anchor spot.
5828 mPointerController->move(deltaX, deltaY);
5829 } else {
5830 mPointerVelocityControl.reset();
5831 }
5832
5833 bool down;
5834 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5835#if DEBUG_GESTURES
5836 ALOGD("Gestures: TAP_DRAG");
5837#endif
5838 down = true;
5839 } else {
5840#if DEBUG_GESTURES
5841 ALOGD("Gestures: HOVER");
5842#endif
5843 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5844 *outFinishPreviousGesture = true;
5845 }
5846 mPointerGesture.activeGestureId = 0;
5847 down = false;
5848 }
5849
5850 float x, y;
5851 mPointerController->getPosition(&x, &y);
5852
5853 mPointerGesture.currentGestureIdBits.clear();
5854 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5855 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5856 mPointerGesture.currentGestureProperties[0].clear();
5857 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5858 mPointerGesture.currentGestureProperties[0].toolType =
5859 AMOTION_EVENT_TOOL_TYPE_FINGER;
5860 mPointerGesture.currentGestureCoords[0].clear();
5861 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5862 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5863 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5864 down ? 1.0f : 0.0f);
5865
5866 if (lastFingerCount == 0 && currentFingerCount != 0) {
5867 mPointerGesture.resetTap();
5868 mPointerGesture.tapDownTime = when;
5869 mPointerGesture.tapX = x;
5870 mPointerGesture.tapY = y;
5871 }
5872 } else {
5873 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5874 // We need to provide feedback for each finger that goes down so we cannot wait
5875 // for the fingers to move before deciding what to do.
5876 //
5877 // The ambiguous case is deciding what to do when there are two fingers down but they
5878 // have not moved enough to determine whether they are part of a drag or part of a
5879 // freeform gesture, or just a press or long-press at the pointer location.
5880 //
5881 // When there are two fingers we start with the PRESS hypothesis and we generate a
5882 // down at the pointer location.
5883 //
5884 // When the two fingers move enough or when additional fingers are added, we make
5885 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5886 ALOG_ASSERT(activeTouchId >= 0);
5887
5888 bool settled = when >= mPointerGesture.firstTouchTime
5889 + mConfig.pointerGestureMultitouchSettleInterval;
5890 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5891 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5892 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5893 *outFinishPreviousGesture = true;
5894 } else if (!settled && currentFingerCount > lastFingerCount) {
5895 // Additional pointers have gone down but not yet settled.
5896 // Reset the gesture.
5897#if DEBUG_GESTURES
5898 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5899 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5900 + mConfig.pointerGestureMultitouchSettleInterval - when)
5901 * 0.000001f);
5902#endif
5903 *outCancelPreviousGesture = true;
5904 } else {
5905 // Continue previous gesture.
5906 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5907 }
5908
5909 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5910 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5911 mPointerGesture.activeGestureId = 0;
5912 mPointerGesture.referenceIdBits.clear();
5913 mPointerVelocityControl.reset();
5914
5915 // Use the centroid and pointer location as the reference points for the gesture.
5916#if DEBUG_GESTURES
5917 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5918 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5919 + mConfig.pointerGestureMultitouchSettleInterval - when)
5920 * 0.000001f);
5921#endif
Michael Wright842500e2015-03-13 17:32:02 -07005922 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 &mPointerGesture.referenceTouchX,
5924 &mPointerGesture.referenceTouchY);
5925 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5926 &mPointerGesture.referenceGestureY);
5927 }
5928
5929 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005930 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005931 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5932 uint32_t id = idBits.clearFirstMarkedBit();
5933 mPointerGesture.referenceDeltas[id].dx = 0;
5934 mPointerGesture.referenceDeltas[id].dy = 0;
5935 }
Michael Wright842500e2015-03-13 17:32:02 -07005936 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005937
5938 // Add delta for all fingers and calculate a common movement delta.
5939 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005940 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5941 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5943 bool first = (idBits == commonIdBits);
5944 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005945 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5946 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5948 delta.dx += cpd.x - lpd.x;
5949 delta.dy += cpd.y - lpd.y;
5950
5951 if (first) {
5952 commonDeltaX = delta.dx;
5953 commonDeltaY = delta.dy;
5954 } else {
5955 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5956 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5957 }
5958 }
5959
5960 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5961 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5962 float dist[MAX_POINTER_ID + 1];
5963 int32_t distOverThreshold = 0;
5964 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5965 uint32_t id = idBits.clearFirstMarkedBit();
5966 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5967 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5968 delta.dy * mPointerYZoomScale);
5969 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5970 distOverThreshold += 1;
5971 }
5972 }
5973
5974 // Only transition when at least two pointers have moved further than
5975 // the minimum distance threshold.
5976 if (distOverThreshold >= 2) {
5977 if (currentFingerCount > 2) {
5978 // There are more than two pointers, switch to FREEFORM.
5979#if DEBUG_GESTURES
5980 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5981 currentFingerCount);
5982#endif
5983 *outCancelPreviousGesture = true;
5984 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5985 } else {
5986 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005987 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005988 uint32_t id1 = idBits.clearFirstMarkedBit();
5989 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005990 const RawPointerData::Pointer& p1 =
5991 mCurrentRawState.rawPointerData.pointerForId(id1);
5992 const RawPointerData::Pointer& p2 =
5993 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005994 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5995 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5996 // There are two pointers but they are too far apart for a SWIPE,
5997 // switch to FREEFORM.
5998#if DEBUG_GESTURES
5999 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
6000 mutualDistance, mPointerGestureMaxSwipeWidth);
6001#endif
6002 *outCancelPreviousGesture = true;
6003 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6004 } else {
6005 // There are two pointers. Wait for both pointers to start moving
6006 // before deciding whether this is a SWIPE or FREEFORM gesture.
6007 float dist1 = dist[id1];
6008 float dist2 = dist[id2];
6009 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
6010 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
6011 // Calculate the dot product of the displacement vectors.
6012 // When the vectors are oriented in approximately the same direction,
6013 // the angle betweeen them is near zero and the cosine of the angle
6014 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
6015 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
6016 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
6017 float dx1 = delta1.dx * mPointerXZoomScale;
6018 float dy1 = delta1.dy * mPointerYZoomScale;
6019 float dx2 = delta2.dx * mPointerXZoomScale;
6020 float dy2 = delta2.dy * mPointerYZoomScale;
6021 float dot = dx1 * dx2 + dy1 * dy2;
6022 float cosine = dot / (dist1 * dist2); // denominator always > 0
6023 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
6024 // Pointers are moving in the same direction. Switch to SWIPE.
6025#if DEBUG_GESTURES
6026 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6027 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6028 "cosine %0.3f >= %0.3f",
6029 dist1, mConfig.pointerGestureMultitouchMinDistance,
6030 dist2, mConfig.pointerGestureMultitouchMinDistance,
6031 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6032#endif
6033 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6034 } else {
6035 // Pointers are moving in different directions. Switch to FREEFORM.
6036#if DEBUG_GESTURES
6037 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6038 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6039 "cosine %0.3f < %0.3f",
6040 dist1, mConfig.pointerGestureMultitouchMinDistance,
6041 dist2, mConfig.pointerGestureMultitouchMinDistance,
6042 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6043#endif
6044 *outCancelPreviousGesture = true;
6045 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6046 }
6047 }
6048 }
6049 }
6050 }
6051 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6052 // Switch from SWIPE to FREEFORM if additional pointers go down.
6053 // Cancel previous gesture.
6054 if (currentFingerCount > 2) {
6055#if DEBUG_GESTURES
6056 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6057 currentFingerCount);
6058#endif
6059 *outCancelPreviousGesture = true;
6060 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6061 }
6062 }
6063
6064 // Move the reference points based on the overall group motion of the fingers
6065 // except in PRESS mode while waiting for a transition to occur.
6066 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6067 && (commonDeltaX || commonDeltaY)) {
6068 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6069 uint32_t id = idBits.clearFirstMarkedBit();
6070 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6071 delta.dx = 0;
6072 delta.dy = 0;
6073 }
6074
6075 mPointerGesture.referenceTouchX += commonDeltaX;
6076 mPointerGesture.referenceTouchY += commonDeltaY;
6077
6078 commonDeltaX *= mPointerXMovementScale;
6079 commonDeltaY *= mPointerYMovementScale;
6080
6081 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6082 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6083
6084 mPointerGesture.referenceGestureX += commonDeltaX;
6085 mPointerGesture.referenceGestureY += commonDeltaY;
6086 }
6087
6088 // Report gestures.
6089 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6090 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6091 // PRESS or SWIPE mode.
6092#if DEBUG_GESTURES
6093 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6094 "activeGestureId=%d, currentTouchPointerCount=%d",
6095 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6096#endif
6097 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6098
6099 mPointerGesture.currentGestureIdBits.clear();
6100 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6101 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6102 mPointerGesture.currentGestureProperties[0].clear();
6103 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6104 mPointerGesture.currentGestureProperties[0].toolType =
6105 AMOTION_EVENT_TOOL_TYPE_FINGER;
6106 mPointerGesture.currentGestureCoords[0].clear();
6107 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6108 mPointerGesture.referenceGestureX);
6109 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6110 mPointerGesture.referenceGestureY);
6111 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6112 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6113 // FREEFORM mode.
6114#if DEBUG_GESTURES
6115 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6116 "activeGestureId=%d, currentTouchPointerCount=%d",
6117 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6118#endif
6119 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6120
6121 mPointerGesture.currentGestureIdBits.clear();
6122
6123 BitSet32 mappedTouchIdBits;
6124 BitSet32 usedGestureIdBits;
6125 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6126 // Initially, assign the active gesture id to the active touch point
6127 // if there is one. No other touch id bits are mapped yet.
6128 if (!*outCancelPreviousGesture) {
6129 mappedTouchIdBits.markBit(activeTouchId);
6130 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6131 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6132 mPointerGesture.activeGestureId;
6133 } else {
6134 mPointerGesture.activeGestureId = -1;
6135 }
6136 } else {
6137 // Otherwise, assume we mapped all touches from the previous frame.
6138 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006139 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6140 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006141 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6142
6143 // Check whether we need to choose a new active gesture id because the
6144 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006145 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6146 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006147 !upTouchIdBits.isEmpty(); ) {
6148 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6149 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6150 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6151 mPointerGesture.activeGestureId = -1;
6152 break;
6153 }
6154 }
6155 }
6156
6157#if DEBUG_GESTURES
6158 ALOGD("Gestures: FREEFORM follow up "
6159 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6160 "activeGestureId=%d",
6161 mappedTouchIdBits.value, usedGestureIdBits.value,
6162 mPointerGesture.activeGestureId);
6163#endif
6164
Michael Wright842500e2015-03-13 17:32:02 -07006165 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006166 for (uint32_t i = 0; i < currentFingerCount; i++) {
6167 uint32_t touchId = idBits.clearFirstMarkedBit();
6168 uint32_t gestureId;
6169 if (!mappedTouchIdBits.hasBit(touchId)) {
6170 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6171 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6172#if DEBUG_GESTURES
6173 ALOGD("Gestures: FREEFORM "
6174 "new mapping for touch id %d -> gesture id %d",
6175 touchId, gestureId);
6176#endif
6177 } else {
6178 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6179#if DEBUG_GESTURES
6180 ALOGD("Gestures: FREEFORM "
6181 "existing mapping for touch id %d -> gesture id %d",
6182 touchId, gestureId);
6183#endif
6184 }
6185 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6186 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6187
6188 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006189 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006190 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6191 * mPointerXZoomScale;
6192 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6193 * mPointerYZoomScale;
6194 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6195
6196 mPointerGesture.currentGestureProperties[i].clear();
6197 mPointerGesture.currentGestureProperties[i].id = gestureId;
6198 mPointerGesture.currentGestureProperties[i].toolType =
6199 AMOTION_EVENT_TOOL_TYPE_FINGER;
6200 mPointerGesture.currentGestureCoords[i].clear();
6201 mPointerGesture.currentGestureCoords[i].setAxisValue(
6202 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6203 mPointerGesture.currentGestureCoords[i].setAxisValue(
6204 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6205 mPointerGesture.currentGestureCoords[i].setAxisValue(
6206 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6207 }
6208
6209 if (mPointerGesture.activeGestureId < 0) {
6210 mPointerGesture.activeGestureId =
6211 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6212#if DEBUG_GESTURES
6213 ALOGD("Gestures: FREEFORM new "
6214 "activeGestureId=%d", mPointerGesture.activeGestureId);
6215#endif
6216 }
6217 }
6218 }
6219
Michael Wright842500e2015-03-13 17:32:02 -07006220 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221
6222#if DEBUG_GESTURES
6223 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6224 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6225 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6226 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6227 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6228 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6229 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6230 uint32_t id = idBits.clearFirstMarkedBit();
6231 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6232 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6233 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6234 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6235 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6236 id, index, properties.toolType,
6237 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6238 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6239 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6240 }
6241 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6242 uint32_t id = idBits.clearFirstMarkedBit();
6243 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6244 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6245 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6246 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6247 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6248 id, index, properties.toolType,
6249 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6250 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6251 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6252 }
6253#endif
6254 return true;
6255}
6256
6257void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6258 mPointerSimple.currentCoords.clear();
6259 mPointerSimple.currentProperties.clear();
6260
6261 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006262 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6263 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6264 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6265 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6266 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 mPointerController->setPosition(x, y);
6268
Michael Wright842500e2015-03-13 17:32:02 -07006269 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 down = !hovering;
6271
6272 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006273 mPointerSimple.currentCoords.copyFrom(
6274 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006275 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6276 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6277 mPointerSimple.currentProperties.id = 0;
6278 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006279 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006280 } else {
6281 down = false;
6282 hovering = false;
6283 }
6284
6285 dispatchPointerSimple(when, policyFlags, down, hovering);
6286}
6287
6288void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6289 abortPointerSimple(when, policyFlags);
6290}
6291
6292void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6293 mPointerSimple.currentCoords.clear();
6294 mPointerSimple.currentProperties.clear();
6295
6296 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006297 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6298 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6299 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006300 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006301 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6302 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006303 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006304 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006306 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006307 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 * mPointerYMovementScale;
6309
6310 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6311 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6312
6313 mPointerController->move(deltaX, deltaY);
6314 } else {
6315 mPointerVelocityControl.reset();
6316 }
6317
Michael Wright842500e2015-03-13 17:32:02 -07006318 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319 hovering = !down;
6320
6321 float x, y;
6322 mPointerController->getPosition(&x, &y);
6323 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006324 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006325 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6326 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6327 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6328 hovering ? 0.0f : 1.0f);
6329 mPointerSimple.currentProperties.id = 0;
6330 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006331 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 } else {
6333 mPointerVelocityControl.reset();
6334
6335 down = false;
6336 hovering = false;
6337 }
6338
6339 dispatchPointerSimple(when, policyFlags, down, hovering);
6340}
6341
6342void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6343 abortPointerSimple(when, policyFlags);
6344
6345 mPointerVelocityControl.reset();
6346}
6347
6348void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6349 bool down, bool hovering) {
6350 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006351 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352
Garfield Tan00f511d2019-06-12 16:55:40 -07006353 if (down || hovering) {
6354 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6355 mPointerController->clearSpots();
6356 mPointerController->setButtonState(mCurrentRawState.buttonState);
6357 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6358 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6359 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006361 displayId = mPointerController->getDisplayId();
6362
6363 float xCursorPosition;
6364 float yCursorPosition;
6365 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006366
6367 if (mPointerSimple.down && !down) {
6368 mPointerSimple.down = false;
6369
6370 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006371 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6372 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6373 mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006374 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6375 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6376 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6377 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006378 getListener()->notifyMotion(&args);
6379 }
6380
6381 if (mPointerSimple.hovering && !hovering) {
6382 mPointerSimple.hovering = false;
6383
6384 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006385 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6386 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6387 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006388 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6389 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6390 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6391 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392 getListener()->notifyMotion(&args);
6393 }
6394
6395 if (down) {
6396 if (!mPointerSimple.down) {
6397 mPointerSimple.down = true;
6398 mPointerSimple.downTime = when;
6399
6400 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006401 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6402 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6403 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006404 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6405 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6406 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6407 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006408 getListener()->notifyMotion(&args);
6409 }
6410
6411 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006412 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6413 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6414 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006415 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6416 &mPointerSimple.currentCoords, mOrientedXPrecision,
6417 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6418 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419 getListener()->notifyMotion(&args);
6420 }
6421
6422 if (hovering) {
6423 if (!mPointerSimple.hovering) {
6424 mPointerSimple.hovering = true;
6425
6426 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006427 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6428 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6429 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006430 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6431 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6432 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6433 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006434 getListener()->notifyMotion(&args);
6435 }
6436
6437 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006438 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6439 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6440 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006441 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6442 &mPointerSimple.currentCoords, mOrientedXPrecision,
6443 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6444 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006445 getListener()->notifyMotion(&args);
6446 }
6447
Michael Wright842500e2015-03-13 17:32:02 -07006448 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6449 float vscroll = mCurrentRawState.rawVScroll;
6450 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006451 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6452 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006453
6454 // Send scroll.
6455 PointerCoords pointerCoords;
6456 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6457 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6458 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6459
Garfield Tan00f511d2019-06-12 16:55:40 -07006460 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6461 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6462 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006463 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6464 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
6465 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6466 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006467 getListener()->notifyMotion(&args);
6468 }
6469
6470 // Save state.
6471 if (down || hovering) {
6472 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6473 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6474 } else {
6475 mPointerSimple.reset();
6476 }
6477}
6478
6479void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6480 mPointerSimple.currentCoords.clear();
6481 mPointerSimple.currentProperties.clear();
6482
6483 dispatchPointerSimple(when, policyFlags, false, false);
6484}
6485
6486void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006487 int32_t action, int32_t actionButton, int32_t flags,
6488 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6489 const PointerProperties* properties,
6490 const PointerCoords* coords, const uint32_t* idToIndex,
6491 BitSet32 idBits, int32_t changedId, float xPrecision,
6492 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493 PointerCoords pointerCoords[MAX_POINTERS];
6494 PointerProperties pointerProperties[MAX_POINTERS];
6495 uint32_t pointerCount = 0;
6496 while (!idBits.isEmpty()) {
6497 uint32_t id = idBits.clearFirstMarkedBit();
6498 uint32_t index = idToIndex[id];
6499 pointerProperties[pointerCount].copyFrom(properties[index]);
6500 pointerCoords[pointerCount].copyFrom(coords[index]);
6501
6502 if (changedId >= 0 && id == uint32_t(changedId)) {
6503 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6504 }
6505
6506 pointerCount += 1;
6507 }
6508
6509 ALOG_ASSERT(pointerCount != 0);
6510
6511 if (changedId >= 0 && pointerCount == 1) {
6512 // Replace initial down and final up action.
6513 // We can compare the action without masking off the changed pointer index
6514 // because we know the index is 0.
6515 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6516 action = AMOTION_EVENT_ACTION_DOWN;
6517 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6518 action = AMOTION_EVENT_ACTION_UP;
6519 } else {
6520 // Can't happen.
6521 ALOG_ASSERT(false);
6522 }
6523 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006524 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6525 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6526 if (mDeviceMode == DEVICE_MODE_POINTER) {
6527 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6528 }
Arthur Hungc23540e2018-11-29 20:42:11 +08006529 const int32_t displayId = getAssociatedDisplay().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006530 const int32_t deviceId = getDeviceId();
6531 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006532 std::for_each(frames.begin(), frames.end(),
6533 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006534 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6535 policyFlags, action, actionButton, flags, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006536 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
6537 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
6538 downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006539 getListener()->notifyMotion(&args);
6540}
6541
6542bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6543 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6544 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6545 BitSet32 idBits) const {
6546 bool changed = false;
6547 while (!idBits.isEmpty()) {
6548 uint32_t id = idBits.clearFirstMarkedBit();
6549 uint32_t inIndex = inIdToIndex[id];
6550 uint32_t outIndex = outIdToIndex[id];
6551
6552 const PointerProperties& curInProperties = inProperties[inIndex];
6553 const PointerCoords& curInCoords = inCoords[inIndex];
6554 PointerProperties& curOutProperties = outProperties[outIndex];
6555 PointerCoords& curOutCoords = outCoords[outIndex];
6556
6557 if (curInProperties != curOutProperties) {
6558 curOutProperties.copyFrom(curInProperties);
6559 changed = true;
6560 }
6561
6562 if (curInCoords != curOutCoords) {
6563 curOutCoords.copyFrom(curInCoords);
6564 changed = true;
6565 }
6566 }
6567 return changed;
6568}
6569
6570void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006571 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6573 }
6574}
6575
Jeff Brownc9aa6282015-02-11 19:03:28 -08006576void TouchInputMapper::cancelTouch(nsecs_t when) {
6577 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006578 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006579}
6580
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006582 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006583 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006585 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6586 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6587 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588}
6589
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006590const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006592 for (const VirtualKey& virtualKey: mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593#if DEBUG_VIRTUAL_KEYS
6594 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6595 "left=%d, top=%d, right=%d, bottom=%d",
6596 x, y,
6597 virtualKey.keyCode, virtualKey.scanCode,
6598 virtualKey.hitLeft, virtualKey.hitTop,
6599 virtualKey.hitRight, virtualKey.hitBottom);
6600#endif
6601
6602 if (virtualKey.isHit(x, y)) {
6603 return & virtualKey;
6604 }
6605 }
6606
Yi Kong9b14ac62018-07-17 13:48:38 -07006607 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006608}
6609
Michael Wright842500e2015-03-13 17:32:02 -07006610void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6611 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6612 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613
Michael Wright842500e2015-03-13 17:32:02 -07006614 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615
6616 if (currentPointerCount == 0) {
6617 // No pointers to assign.
6618 return;
6619 }
6620
6621 if (lastPointerCount == 0) {
6622 // All pointers are new.
6623 for (uint32_t i = 0; i < currentPointerCount; i++) {
6624 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006625 current->rawPointerData.pointers[i].id = id;
6626 current->rawPointerData.idToIndex[id] = i;
6627 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 }
6629 return;
6630 }
6631
6632 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006633 && current->rawPointerData.pointers[0].toolType
6634 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006635 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006636 uint32_t id = last->rawPointerData.pointers[0].id;
6637 current->rawPointerData.pointers[0].id = id;
6638 current->rawPointerData.idToIndex[id] = 0;
6639 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006640 return;
6641 }
6642
6643 // General case.
6644 // We build a heap of squared euclidean distances between current and last pointers
6645 // associated with the current and last pointer indices. Then, we find the best
6646 // match (by distance) for each current pointer.
6647 // The pointers must have the same tool type but it is possible for them to
6648 // transition from hovering to touching or vice-versa while retaining the same id.
6649 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6650
6651 uint32_t heapSize = 0;
6652 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6653 currentPointerIndex++) {
6654 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6655 lastPointerIndex++) {
6656 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006657 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006658 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006659 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006660 if (currentPointer.toolType == lastPointer.toolType) {
6661 int64_t deltaX = currentPointer.x - lastPointer.x;
6662 int64_t deltaY = currentPointer.y - lastPointer.y;
6663
6664 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6665
6666 // Insert new element into the heap (sift up).
6667 heap[heapSize].currentPointerIndex = currentPointerIndex;
6668 heap[heapSize].lastPointerIndex = lastPointerIndex;
6669 heap[heapSize].distance = distance;
6670 heapSize += 1;
6671 }
6672 }
6673 }
6674
6675 // Heapify
6676 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6677 startIndex -= 1;
6678 for (uint32_t parentIndex = startIndex; ;) {
6679 uint32_t childIndex = parentIndex * 2 + 1;
6680 if (childIndex >= heapSize) {
6681 break;
6682 }
6683
6684 if (childIndex + 1 < heapSize
6685 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6686 childIndex += 1;
6687 }
6688
6689 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6690 break;
6691 }
6692
6693 swap(heap[parentIndex], heap[childIndex]);
6694 parentIndex = childIndex;
6695 }
6696 }
6697
6698#if DEBUG_POINTER_ASSIGNMENT
6699 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6700 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006701 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006702 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6703 heap[i].distance);
6704 }
6705#endif
6706
6707 // Pull matches out by increasing order of distance.
6708 // To avoid reassigning pointers that have already been matched, the loop keeps track
6709 // of which last and current pointers have been matched using the matchedXXXBits variables.
6710 // It also tracks the used pointer id bits.
6711 BitSet32 matchedLastBits(0);
6712 BitSet32 matchedCurrentBits(0);
6713 BitSet32 usedIdBits(0);
6714 bool first = true;
6715 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6716 while (heapSize > 0) {
6717 if (first) {
6718 // The first time through the loop, we just consume the root element of
6719 // the heap (the one with smallest distance).
6720 first = false;
6721 } else {
6722 // Previous iterations consumed the root element of the heap.
6723 // Pop root element off of the heap (sift down).
6724 heap[0] = heap[heapSize];
6725 for (uint32_t parentIndex = 0; ;) {
6726 uint32_t childIndex = parentIndex * 2 + 1;
6727 if (childIndex >= heapSize) {
6728 break;
6729 }
6730
6731 if (childIndex + 1 < heapSize
6732 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6733 childIndex += 1;
6734 }
6735
6736 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6737 break;
6738 }
6739
6740 swap(heap[parentIndex], heap[childIndex]);
6741 parentIndex = childIndex;
6742 }
6743
6744#if DEBUG_POINTER_ASSIGNMENT
6745 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6746 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006747 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006748 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6749 heap[i].distance);
6750 }
6751#endif
6752 }
6753
6754 heapSize -= 1;
6755
6756 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6757 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6758
6759 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6760 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6761
6762 matchedCurrentBits.markBit(currentPointerIndex);
6763 matchedLastBits.markBit(lastPointerIndex);
6764
Michael Wright842500e2015-03-13 17:32:02 -07006765 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6766 current->rawPointerData.pointers[currentPointerIndex].id = id;
6767 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6768 current->rawPointerData.markIdBit(id,
6769 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006770 usedIdBits.markBit(id);
6771
6772#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006773 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6774 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006775 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6776#endif
6777 break;
6778 }
6779 }
6780
6781 // Assign fresh ids to pointers that were not matched in the process.
6782 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6783 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6784 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6785
Michael Wright842500e2015-03-13 17:32:02 -07006786 current->rawPointerData.pointers[currentPointerIndex].id = id;
6787 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6788 current->rawPointerData.markIdBit(id,
6789 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006790
6791#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006792 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006793#endif
6794 }
6795}
6796
6797int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6798 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6799 return AKEY_STATE_VIRTUAL;
6800 }
6801
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006802 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006803 if (virtualKey.keyCode == keyCode) {
6804 return AKEY_STATE_UP;
6805 }
6806 }
6807
6808 return AKEY_STATE_UNKNOWN;
6809}
6810
6811int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6812 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6813 return AKEY_STATE_VIRTUAL;
6814 }
6815
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006816 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006817 if (virtualKey.scanCode == scanCode) {
6818 return AKEY_STATE_UP;
6819 }
6820 }
6821
6822 return AKEY_STATE_UNKNOWN;
6823}
6824
6825bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6826 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006827 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006828 for (size_t i = 0; i < numCodes; i++) {
6829 if (virtualKey.keyCode == keyCodes[i]) {
6830 outFlags[i] = 1;
6831 }
6832 }
6833 }
6834
6835 return true;
6836}
6837
Arthur Hungc23540e2018-11-29 20:42:11 +08006838std::optional<int32_t> TouchInputMapper::getAssociatedDisplay() {
6839 if (mParameters.hasAssociatedDisplay) {
6840 if (mDeviceMode == DEVICE_MODE_POINTER) {
6841 return std::make_optional(mPointerController->getDisplayId());
6842 } else {
6843 return std::make_optional(mViewport.displayId);
6844 }
6845 }
6846 return std::nullopt;
6847}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006848
6849// --- SingleTouchInputMapper ---
6850
6851SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6852 TouchInputMapper(device) {
6853}
6854
6855SingleTouchInputMapper::~SingleTouchInputMapper() {
6856}
6857
6858void SingleTouchInputMapper::reset(nsecs_t when) {
6859 mSingleTouchMotionAccumulator.reset(getDevice());
6860
6861 TouchInputMapper::reset(when);
6862}
6863
6864void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6865 TouchInputMapper::process(rawEvent);
6866
6867 mSingleTouchMotionAccumulator.process(rawEvent);
6868}
6869
Michael Wright842500e2015-03-13 17:32:02 -07006870void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006871 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006872 outState->rawPointerData.pointerCount = 1;
6873 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006874
6875 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6876 && (mTouchButtonAccumulator.isHovering()
6877 || (mRawPointerAxes.pressure.valid
6878 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006879 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006880
Michael Wright842500e2015-03-13 17:32:02 -07006881 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006882 outPointer.id = 0;
6883 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6884 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6885 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6886 outPointer.touchMajor = 0;
6887 outPointer.touchMinor = 0;
6888 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6889 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6890 outPointer.orientation = 0;
6891 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6892 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6893 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6894 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6895 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6896 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6897 }
6898 outPointer.isHovering = isHovering;
6899 }
6900}
6901
6902void SingleTouchInputMapper::configureRawPointerAxes() {
6903 TouchInputMapper::configureRawPointerAxes();
6904
6905 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6906 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6907 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6908 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6909 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6910 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6911 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6912}
6913
6914bool SingleTouchInputMapper::hasStylus() const {
6915 return mTouchButtonAccumulator.hasStylus();
6916}
6917
6918
6919// --- MultiTouchInputMapper ---
6920
6921MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6922 TouchInputMapper(device) {
6923}
6924
6925MultiTouchInputMapper::~MultiTouchInputMapper() {
6926}
6927
6928void MultiTouchInputMapper::reset(nsecs_t when) {
6929 mMultiTouchMotionAccumulator.reset(getDevice());
6930
6931 mPointerIdBits.clear();
6932
6933 TouchInputMapper::reset(when);
6934}
6935
6936void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6937 TouchInputMapper::process(rawEvent);
6938
6939 mMultiTouchMotionAccumulator.process(rawEvent);
6940}
6941
Michael Wright842500e2015-03-13 17:32:02 -07006942void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006943 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6944 size_t outCount = 0;
6945 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006946 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006947
6948 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6949 const MultiTouchMotionAccumulator::Slot* inSlot =
6950 mMultiTouchMotionAccumulator.getSlot(inIndex);
6951 if (!inSlot->isInUse()) {
6952 continue;
6953 }
6954
6955 if (outCount >= MAX_POINTERS) {
6956#if DEBUG_POINTERS
6957 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6958 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006959 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006960#endif
6961 break; // too many fingers!
6962 }
6963
Michael Wright842500e2015-03-13 17:32:02 -07006964 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006965 outPointer.x = inSlot->getX();
6966 outPointer.y = inSlot->getY();
6967 outPointer.pressure = inSlot->getPressure();
6968 outPointer.touchMajor = inSlot->getTouchMajor();
6969 outPointer.touchMinor = inSlot->getTouchMinor();
6970 outPointer.toolMajor = inSlot->getToolMajor();
6971 outPointer.toolMinor = inSlot->getToolMinor();
6972 outPointer.orientation = inSlot->getOrientation();
6973 outPointer.distance = inSlot->getDistance();
6974 outPointer.tiltX = 0;
6975 outPointer.tiltY = 0;
6976
6977 outPointer.toolType = inSlot->getToolType();
6978 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6979 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6980 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6981 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6982 }
6983 }
6984
6985 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6986 && (mTouchButtonAccumulator.isHovering()
6987 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6988 outPointer.isHovering = isHovering;
6989
6990 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006991 if (mHavePointerIds) {
6992 int32_t trackingId = inSlot->getTrackingId();
6993 int32_t id = -1;
6994 if (trackingId >= 0) {
6995 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6996 uint32_t n = idBits.clearFirstMarkedBit();
6997 if (mPointerTrackingIdMap[n] == trackingId) {
6998 id = n;
6999 }
7000 }
7001
7002 if (id < 0 && !mPointerIdBits.isFull()) {
7003 id = mPointerIdBits.markFirstUnmarkedBit();
7004 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007005 }
Michael Wright842500e2015-03-13 17:32:02 -07007006 }
gaoshang1a632de2016-08-24 10:23:50 +08007007 if (id < 0) {
7008 mHavePointerIds = false;
7009 outState->rawPointerData.clearIdBits();
7010 newPointerIdBits.clear();
7011 } else {
7012 outPointer.id = id;
7013 outState->rawPointerData.idToIndex[id] = outCount;
7014 outState->rawPointerData.markIdBit(id, isHovering);
7015 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007016 }
Michael Wright842500e2015-03-13 17:32:02 -07007017 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007018 outCount += 1;
7019 }
7020
Michael Wright842500e2015-03-13 17:32:02 -07007021 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007022 mPointerIdBits = newPointerIdBits;
7023
7024 mMultiTouchMotionAccumulator.finishSync();
7025}
7026
7027void MultiTouchInputMapper::configureRawPointerAxes() {
7028 TouchInputMapper::configureRawPointerAxes();
7029
7030 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7031 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7032 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7033 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7034 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7035 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7036 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7037 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7038 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7039 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7040 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7041
7042 if (mRawPointerAxes.trackingId.valid
7043 && mRawPointerAxes.slot.valid
7044 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7045 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7046 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007047 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7048 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007049 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007050 slotCount = MAX_SLOTS;
7051 }
7052 mMultiTouchMotionAccumulator.configure(getDevice(),
7053 slotCount, true /*usingSlotsProtocol*/);
7054 } else {
7055 mMultiTouchMotionAccumulator.configure(getDevice(),
7056 MAX_POINTERS, false /*usingSlotsProtocol*/);
7057 }
7058}
7059
7060bool MultiTouchInputMapper::hasStylus() const {
7061 return mMultiTouchMotionAccumulator.hasStylus()
7062 || mTouchButtonAccumulator.hasStylus();
7063}
7064
Michael Wright842500e2015-03-13 17:32:02 -07007065// --- ExternalStylusInputMapper
7066
7067ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7068 InputMapper(device) {
7069
7070}
7071
7072uint32_t ExternalStylusInputMapper::getSources() {
7073 return AINPUT_SOURCE_STYLUS;
7074}
7075
7076void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7077 InputMapper::populateDeviceInfo(info);
7078 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7079 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7080}
7081
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007082void ExternalStylusInputMapper::dump(std::string& dump) {
7083 dump += INDENT2 "External Stylus Input Mapper:\n";
7084 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007085 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007086 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007087 dumpStylusState(dump, mStylusState);
7088}
7089
7090void ExternalStylusInputMapper::configure(nsecs_t when,
7091 const InputReaderConfiguration* config, uint32_t changes) {
7092 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7093 mTouchButtonAccumulator.configure(getDevice());
7094}
7095
7096void ExternalStylusInputMapper::reset(nsecs_t when) {
7097 InputDevice* device = getDevice();
7098 mSingleTouchMotionAccumulator.reset(device);
7099 mTouchButtonAccumulator.reset(device);
7100 InputMapper::reset(when);
7101}
7102
7103void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7104 mSingleTouchMotionAccumulator.process(rawEvent);
7105 mTouchButtonAccumulator.process(rawEvent);
7106
7107 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7108 sync(rawEvent->when);
7109 }
7110}
7111
7112void ExternalStylusInputMapper::sync(nsecs_t when) {
7113 mStylusState.clear();
7114
7115 mStylusState.when = when;
7116
Michael Wright45ccacf2015-04-21 19:01:58 +01007117 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7118 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7119 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7120 }
7121
Michael Wright842500e2015-03-13 17:32:02 -07007122 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7123 if (mRawPressureAxis.valid) {
7124 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7125 } else if (mTouchButtonAccumulator.isToolActive()) {
7126 mStylusState.pressure = 1.0f;
7127 } else {
7128 mStylusState.pressure = 0.0f;
7129 }
7130
7131 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007132
7133 mContext->dispatchExternalStylusState(mStylusState);
7134}
7135
Michael Wrightd02c5b62014-02-10 15:10:22 -08007136
7137// --- JoystickInputMapper ---
7138
7139JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7140 InputMapper(device) {
7141}
7142
7143JoystickInputMapper::~JoystickInputMapper() {
7144}
7145
7146uint32_t JoystickInputMapper::getSources() {
7147 return AINPUT_SOURCE_JOYSTICK;
7148}
7149
7150void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7151 InputMapper::populateDeviceInfo(info);
7152
7153 for (size_t i = 0; i < mAxes.size(); i++) {
7154 const Axis& axis = mAxes.valueAt(i);
7155 addMotionRange(axis.axisInfo.axis, axis, info);
7156
7157 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7158 addMotionRange(axis.axisInfo.highAxis, axis, info);
7159
7160 }
7161 }
7162}
7163
7164void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7165 InputDeviceInfo* info) {
7166 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7167 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7168 /* In order to ease the transition for developers from using the old axes
7169 * to the newer, more semantically correct axes, we'll continue to register
7170 * the old axes as duplicates of their corresponding new ones. */
7171 int32_t compatAxis = getCompatAxis(axisId);
7172 if (compatAxis >= 0) {
7173 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7174 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7175 }
7176}
7177
7178/* A mapping from axes the joystick actually has to the axes that should be
7179 * artificially created for compatibility purposes.
7180 * Returns -1 if no compatibility axis is needed. */
7181int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7182 switch(axis) {
7183 case AMOTION_EVENT_AXIS_LTRIGGER:
7184 return AMOTION_EVENT_AXIS_BRAKE;
7185 case AMOTION_EVENT_AXIS_RTRIGGER:
7186 return AMOTION_EVENT_AXIS_GAS;
7187 }
7188 return -1;
7189}
7190
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007191void JoystickInputMapper::dump(std::string& dump) {
7192 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007193
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007194 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007195 size_t numAxes = mAxes.size();
7196 for (size_t i = 0; i < numAxes; i++) {
7197 const Axis& axis = mAxes.valueAt(i);
7198 const char* label = getAxisLabel(axis.axisInfo.axis);
7199 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007200 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007201 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007202 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007203 }
7204 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7205 label = getAxisLabel(axis.axisInfo.highAxis);
7206 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007207 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007208 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007209 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007210 axis.axisInfo.splitValue);
7211 }
7212 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007213 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007214 }
7215
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007216 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 -08007217 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007218 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007219 "highScale=%0.5f, highOffset=%0.5f\n",
7220 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007221 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007222 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7223 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7224 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7225 }
7226}
7227
7228void JoystickInputMapper::configure(nsecs_t when,
7229 const InputReaderConfiguration* config, uint32_t changes) {
7230 InputMapper::configure(when, config, changes);
7231
7232 if (!changes) { // first time only
7233 // Collect all axes.
7234 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7235 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7236 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7237 continue; // axis must be claimed by a different device
7238 }
7239
7240 RawAbsoluteAxisInfo rawAxisInfo;
7241 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7242 if (rawAxisInfo.valid) {
7243 // Map axis.
7244 AxisInfo axisInfo;
7245 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7246 if (!explicitlyMapped) {
7247 // Axis is not explicitly mapped, will choose a generic axis later.
7248 axisInfo.mode = AxisInfo::MODE_NORMAL;
7249 axisInfo.axis = -1;
7250 }
7251
7252 // Apply flat override.
7253 int32_t rawFlat = axisInfo.flatOverride < 0
7254 ? rawAxisInfo.flat : axisInfo.flatOverride;
7255
7256 // Calculate scaling factors and limits.
7257 Axis axis;
7258 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7259 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7260 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7261 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7262 scale, 0.0f, highScale, 0.0f,
7263 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7264 rawAxisInfo.resolution * scale);
7265 } else if (isCenteredAxis(axisInfo.axis)) {
7266 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7267 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7268 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7269 scale, offset, scale, offset,
7270 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7271 rawAxisInfo.resolution * scale);
7272 } else {
7273 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7274 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7275 scale, 0.0f, scale, 0.0f,
7276 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7277 rawAxisInfo.resolution * scale);
7278 }
7279
7280 // To eliminate noise while the joystick is at rest, filter out small variations
7281 // in axis values up front.
7282 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7283
7284 mAxes.add(abs, axis);
7285 }
7286 }
7287
7288 // If there are too many axes, start dropping them.
7289 // Prefer to keep explicitly mapped axes.
7290 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007291 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007292 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007293 pruneAxes(true);
7294 pruneAxes(false);
7295 }
7296
7297 // Assign generic axis ids to remaining axes.
7298 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7299 size_t numAxes = mAxes.size();
7300 for (size_t i = 0; i < numAxes; i++) {
7301 Axis& axis = mAxes.editValueAt(i);
7302 if (axis.axisInfo.axis < 0) {
7303 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7304 && haveAxis(nextGenericAxisId)) {
7305 nextGenericAxisId += 1;
7306 }
7307
7308 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7309 axis.axisInfo.axis = nextGenericAxisId;
7310 nextGenericAxisId += 1;
7311 } else {
7312 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7313 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007314 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007315 mAxes.removeItemsAt(i--);
7316 numAxes -= 1;
7317 }
7318 }
7319 }
7320 }
7321}
7322
7323bool JoystickInputMapper::haveAxis(int32_t axisId) {
7324 size_t numAxes = mAxes.size();
7325 for (size_t i = 0; i < numAxes; i++) {
7326 const Axis& axis = mAxes.valueAt(i);
7327 if (axis.axisInfo.axis == axisId
7328 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7329 && axis.axisInfo.highAxis == axisId)) {
7330 return true;
7331 }
7332 }
7333 return false;
7334}
7335
7336void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7337 size_t i = mAxes.size();
7338 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7339 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7340 continue;
7341 }
7342 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007343 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007344 mAxes.removeItemsAt(i);
7345 }
7346}
7347
7348bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7349 switch (axis) {
7350 case AMOTION_EVENT_AXIS_X:
7351 case AMOTION_EVENT_AXIS_Y:
7352 case AMOTION_EVENT_AXIS_Z:
7353 case AMOTION_EVENT_AXIS_RX:
7354 case AMOTION_EVENT_AXIS_RY:
7355 case AMOTION_EVENT_AXIS_RZ:
7356 case AMOTION_EVENT_AXIS_HAT_X:
7357 case AMOTION_EVENT_AXIS_HAT_Y:
7358 case AMOTION_EVENT_AXIS_ORIENTATION:
7359 case AMOTION_EVENT_AXIS_RUDDER:
7360 case AMOTION_EVENT_AXIS_WHEEL:
7361 return true;
7362 default:
7363 return false;
7364 }
7365}
7366
7367void JoystickInputMapper::reset(nsecs_t when) {
7368 // Recenter all axes.
7369 size_t numAxes = mAxes.size();
7370 for (size_t i = 0; i < numAxes; i++) {
7371 Axis& axis = mAxes.editValueAt(i);
7372 axis.resetValue();
7373 }
7374
7375 InputMapper::reset(when);
7376}
7377
7378void JoystickInputMapper::process(const RawEvent* rawEvent) {
7379 switch (rawEvent->type) {
7380 case EV_ABS: {
7381 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7382 if (index >= 0) {
7383 Axis& axis = mAxes.editValueAt(index);
7384 float newValue, highNewValue;
7385 switch (axis.axisInfo.mode) {
7386 case AxisInfo::MODE_INVERT:
7387 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7388 * axis.scale + axis.offset;
7389 highNewValue = 0.0f;
7390 break;
7391 case AxisInfo::MODE_SPLIT:
7392 if (rawEvent->value < axis.axisInfo.splitValue) {
7393 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7394 * axis.scale + axis.offset;
7395 highNewValue = 0.0f;
7396 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7397 newValue = 0.0f;
7398 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7399 * axis.highScale + axis.highOffset;
7400 } else {
7401 newValue = 0.0f;
7402 highNewValue = 0.0f;
7403 }
7404 break;
7405 default:
7406 newValue = rawEvent->value * axis.scale + axis.offset;
7407 highNewValue = 0.0f;
7408 break;
7409 }
7410 axis.newValue = newValue;
7411 axis.highNewValue = highNewValue;
7412 }
7413 break;
7414 }
7415
7416 case EV_SYN:
7417 switch (rawEvent->code) {
7418 case SYN_REPORT:
7419 sync(rawEvent->when, false /*force*/);
7420 break;
7421 }
7422 break;
7423 }
7424}
7425
7426void JoystickInputMapper::sync(nsecs_t when, bool force) {
7427 if (!filterAxes(force)) {
7428 return;
7429 }
7430
7431 int32_t metaState = mContext->getGlobalMetaState();
7432 int32_t buttonState = 0;
7433
7434 PointerProperties pointerProperties;
7435 pointerProperties.clear();
7436 pointerProperties.id = 0;
7437 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7438
7439 PointerCoords pointerCoords;
7440 pointerCoords.clear();
7441
7442 size_t numAxes = mAxes.size();
7443 for (size_t i = 0; i < numAxes; i++) {
7444 const Axis& axis = mAxes.valueAt(i);
7445 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7446 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7447 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7448 axis.highCurrentValue);
7449 }
7450 }
7451
7452 // Moving a joystick axis should not wake the device because joysticks can
7453 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7454 // button will likely wake the device.
7455 // TODO: Use the input device configuration to control this behavior more finely.
7456 uint32_t policyFlags = 0;
7457
Prabir Pradhan42611e02018-11-27 14:04:02 -08007458 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007459 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7460 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07007461 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
7462 &pointerProperties, &pointerCoords, 0, 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07007463 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7464 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007465 getListener()->notifyMotion(&args);
7466}
7467
7468void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7469 int32_t axis, float value) {
7470 pointerCoords->setAxisValue(axis, value);
7471 /* In order to ease the transition for developers from using the old axes
7472 * to the newer, more semantically correct axes, we'll continue to produce
7473 * values for the old axes as mirrors of the value of their corresponding
7474 * new axes. */
7475 int32_t compatAxis = getCompatAxis(axis);
7476 if (compatAxis >= 0) {
7477 pointerCoords->setAxisValue(compatAxis, value);
7478 }
7479}
7480
7481bool JoystickInputMapper::filterAxes(bool force) {
7482 bool atLeastOneSignificantChange = force;
7483 size_t numAxes = mAxes.size();
7484 for (size_t i = 0; i < numAxes; i++) {
7485 Axis& axis = mAxes.editValueAt(i);
7486 if (force || hasValueChangedSignificantly(axis.filter,
7487 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7488 axis.currentValue = axis.newValue;
7489 atLeastOneSignificantChange = true;
7490 }
7491 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7492 if (force || hasValueChangedSignificantly(axis.filter,
7493 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7494 axis.highCurrentValue = axis.highNewValue;
7495 atLeastOneSignificantChange = true;
7496 }
7497 }
7498 }
7499 return atLeastOneSignificantChange;
7500}
7501
7502bool JoystickInputMapper::hasValueChangedSignificantly(
7503 float filter, float newValue, float currentValue, float min, float max) {
7504 if (newValue != currentValue) {
7505 // Filter out small changes in value unless the value is converging on the axis
7506 // bounds or center point. This is intended to reduce the amount of information
7507 // sent to applications by particularly noisy joysticks (such as PS3).
7508 if (fabs(newValue - currentValue) > filter
7509 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7510 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7511 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7512 return true;
7513 }
7514 }
7515 return false;
7516}
7517
7518bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7519 float filter, float newValue, float currentValue, float thresholdValue) {
7520 float newDistance = fabs(newValue - thresholdValue);
7521 if (newDistance < filter) {
7522 float oldDistance = fabs(currentValue - thresholdValue);
7523 if (newDistance < oldDistance) {
7524 return true;
7525 }
7526 }
7527 return false;
7528}
7529
7530} // namespace android