blob: 7e00f420cced0aa32b336ee78cecf413392a6c7f [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>
Michael Wrightd02c5b62014-02-10 15:10:22 -080060
61#define INDENT " "
62#define INDENT2 " "
63#define INDENT3 " "
64#define INDENT4 " "
65#define INDENT5 " "
66
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -080067using android::base::StringPrintf;
68
Michael Wrightd02c5b62014-02-10 15:10:22 -080069namespace android {
70
71// --- Constants ---
72
73// Maximum number of slots supported when using the slot-based Multitouch Protocol B.
74static const size_t MAX_SLOTS = 32;
75
Michael Wright842500e2015-03-13 17:32:02 -070076// Maximum amount of latency to add to touch events while waiting for data from an
77// external stylus.
Michael Wright5e17a5d2015-04-21 22:45:13 +010078static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
Michael Wright842500e2015-03-13 17:32:02 -070079
Michael Wright43fd19f2015-04-21 19:02:58 +010080// Maximum amount of time to wait on touch data before pushing out new pressure data.
81static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
82
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
85static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
89template<typename T>
90inline static T abs(const T& value) {
91 return value < 0 ? - value : value;
92}
93
94template<typename T>
95inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
99template<typename T>
100inline static void swap(T& a, T& b) {
101 T temp = a;
102 a = b;
103 b = temp;
104}
105
106inline static float avg(float x, float y) {
107 return (x + y) / 2;
108}
109
110inline static float distance(float x1, float y1, float x2, float y2) {
111 return hypotf(x1 - x2, y1 - y2);
112}
113
114inline static int32_t signExtendNybble(int32_t value) {
115 return value >= 8 ? value - 16 : value;
116}
117
118static inline const char* toString(bool value) {
119 return value ? "true" : "false";
120}
121
122static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation,
123 const int32_t map[][4], size_t mapSize) {
124 if (orientation != DISPLAY_ORIENTATION_0) {
125 for (size_t i = 0; i < mapSize; i++) {
126 if (value == map[i][0]) {
127 return map[i][orientation];
128 }
129 }
130 }
131 return value;
132}
133
134static const int32_t keyCodeRotationMap[][4] = {
135 // key codes enumerated counter-clockwise with the original (unrotated) key first
136 // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation
137 { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT },
138 { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN },
139 { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT },
140 { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP },
Jim Millere7a57d12016-06-22 15:58:31 -0700141 { AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT,
142 AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT },
143 { AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP,
144 AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN },
145 { AKEYCODE_SYSTEM_NAVIGATION_UP, AKEYCODE_SYSTEM_NAVIGATION_LEFT,
146 AKEYCODE_SYSTEM_NAVIGATION_DOWN, AKEYCODE_SYSTEM_NAVIGATION_RIGHT },
147 { AKEYCODE_SYSTEM_NAVIGATION_LEFT, AKEYCODE_SYSTEM_NAVIGATION_DOWN,
148 AKEYCODE_SYSTEM_NAVIGATION_RIGHT, AKEYCODE_SYSTEM_NAVIGATION_UP },
Michael Wrightd02c5b62014-02-10 15:10:22 -0800149};
150static const size_t keyCodeRotationMapSize =
151 sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]);
152
Ivan Podogovb9afef32017-02-13 15:34:32 +0000153static int32_t rotateStemKey(int32_t value, int32_t orientation,
154 const int32_t map[][2], size_t mapSize) {
155 if (orientation == DISPLAY_ORIENTATION_180) {
156 for (size_t i = 0; i < mapSize; i++) {
157 if (value == map[i][0]) {
158 return map[i][1];
159 }
160 }
161 }
162 return value;
163}
164
165// The mapping can be defined using input device configuration properties keyboard.rotated.stem_X
166static int32_t stemKeyRotationMap[][2] = {
167 // key codes enumerated with the original (unrotated) key first
168 // no rotation, 180 degree rotation
169 { AKEYCODE_STEM_PRIMARY, AKEYCODE_STEM_PRIMARY },
170 { AKEYCODE_STEM_1, AKEYCODE_STEM_1 },
171 { AKEYCODE_STEM_2, AKEYCODE_STEM_2 },
172 { AKEYCODE_STEM_3, AKEYCODE_STEM_3 },
173};
174static const size_t stemKeyRotationMapSize =
175 sizeof(stemKeyRotationMap) / sizeof(stemKeyRotationMap[0]);
176
Michael Wrightd02c5b62014-02-10 15:10:22 -0800177static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000178 keyCode = rotateStemKey(keyCode, orientation,
179 stemKeyRotationMap, stemKeyRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800180 return rotateValueUsingRotationMap(keyCode, orientation,
181 keyCodeRotationMap, keyCodeRotationMapSize);
182}
183
184static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
185 float temp;
186 switch (orientation) {
187 case DISPLAY_ORIENTATION_90:
188 temp = *deltaX;
189 *deltaX = *deltaY;
190 *deltaY = -temp;
191 break;
192
193 case DISPLAY_ORIENTATION_180:
194 *deltaX = -*deltaX;
195 *deltaY = -*deltaY;
196 break;
197
198 case DISPLAY_ORIENTATION_270:
199 temp = *deltaX;
200 *deltaX = -*deltaY;
201 *deltaY = temp;
202 break;
203 }
204}
205
206static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
207 return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0;
208}
209
210// Returns true if the pointer should be reported as being down given the specified
211// button states. This determines whether the event is reported as a touch event.
212static bool isPointerDown(int32_t buttonState) {
213 return buttonState &
214 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY
215 | AMOTION_EVENT_BUTTON_TERTIARY);
216}
217
218static float calculateCommonVector(float a, float b) {
219 if (a > 0 && b > 0) {
220 return a < b ? a : b;
221 } else if (a < 0 && b < 0) {
222 return a > b ? a : b;
223 } else {
224 return 0;
225 }
226}
227
228static void synthesizeButtonKey(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100229 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800230 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState,
231 int32_t buttonState, int32_t keyCode) {
232 if (
233 (action == AKEY_EVENT_ACTION_DOWN
234 && !(lastButtonState & buttonState)
235 && (currentButtonState & buttonState))
236 || (action == AKEY_EVENT_ACTION_UP
237 && (lastButtonState & buttonState)
238 && !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800239 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
240 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100246 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100251 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700257
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258// --- InputReader ---
259
260InputReader::InputReader(const sp<EventHubInterface>& eventHub,
261 const sp<InputReaderPolicyInterface>& policy,
262 const sp<InputListenerInterface>& listener) :
263 mContext(this), mEventHub(eventHub), mPolicy(policy),
Prabir Pradhan42611e02018-11-27 14:04:02 -0800264 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800265 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
266 mConfigurationChangesToRefresh(0) {
267 mQueuedListener = new QueuedInputListener(listener);
268
269 { // acquire lock
270 AutoMutex _l(mLock);
271
272 refreshConfigurationLocked(0);
273 updateGlobalMetaStateLocked();
274 } // release lock
275}
276
277InputReader::~InputReader() {
278 for (size_t i = 0; i < mDevices.size(); i++) {
279 delete mDevices.valueAt(i);
280 }
281}
282
283void InputReader::loopOnce() {
284 int32_t oldGeneration;
285 int32_t timeoutMillis;
286 bool inputDevicesChanged = false;
287 Vector<InputDeviceInfo> inputDevices;
288 { // acquire lock
289 AutoMutex _l(mLock);
290
291 oldGeneration = mGeneration;
292 timeoutMillis = -1;
293
294 uint32_t changes = mConfigurationChangesToRefresh;
295 if (changes) {
296 mConfigurationChangesToRefresh = 0;
297 timeoutMillis = 0;
298 refreshConfigurationLocked(changes);
299 } else if (mNextTimeout != LLONG_MAX) {
300 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
301 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
302 }
303 } // release lock
304
305 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
306
307 { // acquire lock
308 AutoMutex _l(mLock);
309 mReaderIsAliveCondition.broadcast();
310
311 if (count) {
312 processEventsLocked(mEventBuffer, count);
313 }
314
315 if (mNextTimeout != LLONG_MAX) {
316 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
317 if (now >= mNextTimeout) {
318#if DEBUG_RAW_EVENTS
319 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
320#endif
321 mNextTimeout = LLONG_MAX;
322 timeoutExpiredLocked(now);
323 }
324 }
325
326 if (oldGeneration != mGeneration) {
327 inputDevicesChanged = true;
328 getInputDevicesLocked(inputDevices);
329 }
330 } // release lock
331
332 // Send out a message that the describes the changed input devices.
333 if (inputDevicesChanged) {
334 mPolicy->notifyInputDevicesChanged(inputDevices);
335 }
336
337 // Flush queued events out to the listener.
338 // This must happen outside of the lock because the listener could potentially call
339 // back into the InputReader's methods, such as getScanCodeState, or become blocked
340 // on another thread similarly waiting to acquire the InputReader lock thereby
341 // resulting in a deadlock. This situation is actually quite plausible because the
342 // listener is actually the input dispatcher, which calls into the window manager,
343 // which occasionally calls into the input reader.
344 mQueuedListener->flush();
345}
346
347void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
348 for (const RawEvent* rawEvent = rawEvents; count;) {
349 int32_t type = rawEvent->type;
350 size_t batchSize = 1;
351 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
352 int32_t deviceId = rawEvent->deviceId;
353 while (batchSize < count) {
354 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
355 || rawEvent[batchSize].deviceId != deviceId) {
356 break;
357 }
358 batchSize += 1;
359 }
360#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700361 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362#endif
363 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
364 } else {
365 switch (rawEvent->type) {
366 case EventHubInterface::DEVICE_ADDED:
367 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
368 break;
369 case EventHubInterface::DEVICE_REMOVED:
370 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::FINISHED_DEVICE_SCAN:
373 handleConfigurationChangedLocked(rawEvent->when);
374 break;
375 default:
376 ALOG_ASSERT(false); // can't happen
377 break;
378 }
379 }
380 count -= batchSize;
381 rawEvent += batchSize;
382 }
383}
384
385void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
386 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
387 if (deviceIndex >= 0) {
388 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
389 return;
390 }
391
392 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
393 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
394 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
395
396 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
397 device->configure(when, &mConfig, 0);
398 device->reset(when);
399
400 if (device->isIgnored()) {
401 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100402 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 } else {
404 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100405 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 }
407
408 mDevices.add(deviceId, device);
409 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700410
411 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
412 notifyExternalStylusPresenceChanged();
413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414}
415
416void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700417 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
419 if (deviceIndex < 0) {
420 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
421 return;
422 }
423
424 device = mDevices.valueAt(deviceIndex);
425 mDevices.removeItemsAt(deviceIndex, 1);
426 bumpGenerationLocked();
427
428 if (device->isIgnored()) {
429 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100430 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 } else {
432 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100433 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 }
435
Michael Wright842500e2015-03-13 17:32:02 -0700436 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
437 notifyExternalStylusPresenceChanged();
438 }
439
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 device->reset(when);
441 delete device;
442}
443
444InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
445 const InputDeviceIdentifier& identifier, uint32_t classes) {
446 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
447 controllerNumber, identifier, classes);
448
449 // External devices.
450 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
451 device->setExternal(true);
452 }
453
Tim Kilbourn063ff532015-04-08 10:26:18 -0700454 // Devices with mics.
455 if (classes & INPUT_DEVICE_CLASS_MIC) {
456 device->setMic(true);
457 }
458
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 // Switch-like devices.
460 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
461 device->addMapper(new SwitchInputMapper(device));
462 }
463
Prashant Malani1941ff52015-08-11 18:29:28 -0700464 // Scroll wheel-like devices.
465 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
466 device->addMapper(new RotaryEncoderInputMapper(device));
467 }
468
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Vibrator-like devices.
470 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
471 device->addMapper(new VibratorInputMapper(device));
472 }
473
474 // Keyboard-like devices.
475 uint32_t keyboardSource = 0;
476 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
477 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
478 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
479 }
480 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
481 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
482 }
483 if (classes & INPUT_DEVICE_CLASS_DPAD) {
484 keyboardSource |= AINPUT_SOURCE_DPAD;
485 }
486 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
487 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
488 }
489
490 if (keyboardSource != 0) {
491 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
492 }
493
494 // Cursor-like devices.
495 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
496 device->addMapper(new CursorInputMapper(device));
497 }
498
499 // Touchscreens and touchpad devices.
500 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
501 device->addMapper(new MultiTouchInputMapper(device));
502 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
503 device->addMapper(new SingleTouchInputMapper(device));
504 }
505
506 // Joystick-like devices.
507 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
508 device->addMapper(new JoystickInputMapper(device));
509 }
510
Michael Wright842500e2015-03-13 17:32:02 -0700511 // External stylus-like devices.
512 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
513 device->addMapper(new ExternalStylusInputMapper(device));
514 }
515
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 return device;
517}
518
519void InputReader::processEventsForDeviceLocked(int32_t deviceId,
520 const RawEvent* rawEvents, size_t count) {
521 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
522 if (deviceIndex < 0) {
523 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
524 return;
525 }
526
527 InputDevice* device = mDevices.valueAt(deviceIndex);
528 if (device->isIgnored()) {
529 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
530 return;
531 }
532
533 device->process(rawEvents, count);
534}
535
536void InputReader::timeoutExpiredLocked(nsecs_t when) {
537 for (size_t i = 0; i < mDevices.size(); i++) {
538 InputDevice* device = mDevices.valueAt(i);
539 if (!device->isIgnored()) {
540 device->timeoutExpired(when);
541 }
542 }
543}
544
545void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
546 // Reset global meta state because it depends on the list of all configured devices.
547 updateGlobalMetaStateLocked();
548
549 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800550 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800551 mQueuedListener->notifyConfigurationChanged(&args);
552}
553
554void InputReader::refreshConfigurationLocked(uint32_t changes) {
555 mPolicy->getReaderConfiguration(&mConfig);
556 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
557
558 if (changes) {
559 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
560 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
561
562 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
563 mEventHub->requestReopenDevices();
564 } else {
565 for (size_t i = 0; i < mDevices.size(); i++) {
566 InputDevice* device = mDevices.valueAt(i);
567 device->configure(now, &mConfig, changes);
568 }
569 }
570 }
571}
572
573void InputReader::updateGlobalMetaStateLocked() {
574 mGlobalMetaState = 0;
575
576 for (size_t i = 0; i < mDevices.size(); i++) {
577 InputDevice* device = mDevices.valueAt(i);
578 mGlobalMetaState |= device->getMetaState();
579 }
580}
581
582int32_t InputReader::getGlobalMetaStateLocked() {
583 return mGlobalMetaState;
584}
585
Michael Wright842500e2015-03-13 17:32:02 -0700586void InputReader::notifyExternalStylusPresenceChanged() {
587 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
588}
589
590void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
591 for (size_t i = 0; i < mDevices.size(); i++) {
592 InputDevice* device = mDevices.valueAt(i);
593 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
594 outDevices.push();
595 device->getDeviceInfo(&outDevices.editTop());
596 }
597 }
598}
599
600void InputReader::dispatchExternalStylusState(const StylusState& state) {
601 for (size_t i = 0; i < mDevices.size(); i++) {
602 InputDevice* device = mDevices.valueAt(i);
603 device->updateExternalStylusState(state);
604 }
605}
606
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
608 mDisableVirtualKeysTimeout = time;
609}
610
611bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
612 InputDevice* device, int32_t keyCode, int32_t scanCode) {
613 if (now < mDisableVirtualKeysTimeout) {
614 ALOGI("Dropping virtual key from device %s because virtual keys are "
615 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100616 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 (mDisableVirtualKeysTimeout - now) * 0.000001,
618 keyCode, scanCode);
619 return true;
620 } else {
621 return false;
622 }
623}
624
625void InputReader::fadePointerLocked() {
626 for (size_t i = 0; i < mDevices.size(); i++) {
627 InputDevice* device = mDevices.valueAt(i);
628 device->fadePointer();
629 }
630}
631
632void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
633 if (when < mNextTimeout) {
634 mNextTimeout = when;
635 mEventHub->wake();
636 }
637}
638
639int32_t InputReader::bumpGenerationLocked() {
640 return ++mGeneration;
641}
642
643void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
644 AutoMutex _l(mLock);
645 getInputDevicesLocked(outInputDevices);
646}
647
648void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
649 outInputDevices.clear();
650
651 size_t numDevices = mDevices.size();
652 for (size_t i = 0; i < numDevices; i++) {
653 InputDevice* device = mDevices.valueAt(i);
654 if (!device->isIgnored()) {
655 outInputDevices.push();
656 device->getDeviceInfo(&outInputDevices.editTop());
657 }
658 }
659}
660
661int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
662 int32_t keyCode) {
663 AutoMutex _l(mLock);
664
665 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
666}
667
668int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
669 int32_t scanCode) {
670 AutoMutex _l(mLock);
671
672 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
673}
674
675int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
676 AutoMutex _l(mLock);
677
678 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
679}
680
681int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
682 GetStateFunc getStateFunc) {
683 int32_t result = AKEY_STATE_UNKNOWN;
684 if (deviceId >= 0) {
685 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
686 if (deviceIndex >= 0) {
687 InputDevice* device = mDevices.valueAt(deviceIndex);
688 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
689 result = (device->*getStateFunc)(sourceMask, code);
690 }
691 }
692 } else {
693 size_t numDevices = mDevices.size();
694 for (size_t i = 0; i < numDevices; i++) {
695 InputDevice* device = mDevices.valueAt(i);
696 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
697 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
698 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
699 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
700 if (currentResult >= AKEY_STATE_DOWN) {
701 return currentResult;
702 } else if (currentResult == AKEY_STATE_UP) {
703 result = currentResult;
704 }
705 }
706 }
707 }
708 return result;
709}
710
Andrii Kulian763a3a42016-03-08 10:46:16 -0800711void InputReader::toggleCapsLockState(int32_t deviceId) {
712 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
713 if (deviceIndex < 0) {
714 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
715 return;
716 }
717
718 InputDevice* device = mDevices.valueAt(deviceIndex);
719 if (device->isIgnored()) {
720 return;
721 }
722
723 device->updateMetaState(AKEYCODE_CAPS_LOCK);
724}
725
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
727 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
728 AutoMutex _l(mLock);
729
730 memset(outFlags, 0, numCodes);
731 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
732}
733
734bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
735 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
736 bool result = false;
737 if (deviceId >= 0) {
738 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
739 if (deviceIndex >= 0) {
740 InputDevice* device = mDevices.valueAt(deviceIndex);
741 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
742 result = device->markSupportedKeyCodes(sourceMask,
743 numCodes, keyCodes, outFlags);
744 }
745 }
746 } else {
747 size_t numDevices = mDevices.size();
748 for (size_t i = 0; i < numDevices; i++) {
749 InputDevice* device = mDevices.valueAt(i);
750 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
751 result |= device->markSupportedKeyCodes(sourceMask,
752 numCodes, keyCodes, outFlags);
753 }
754 }
755 }
756 return result;
757}
758
759void InputReader::requestRefreshConfiguration(uint32_t changes) {
760 AutoMutex _l(mLock);
761
762 if (changes) {
763 bool needWake = !mConfigurationChangesToRefresh;
764 mConfigurationChangesToRefresh |= changes;
765
766 if (needWake) {
767 mEventHub->wake();
768 }
769 }
770}
771
772void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
773 ssize_t repeat, int32_t token) {
774 AutoMutex _l(mLock);
775
776 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
777 if (deviceIndex >= 0) {
778 InputDevice* device = mDevices.valueAt(deviceIndex);
779 device->vibrate(pattern, patternSize, repeat, token);
780 }
781}
782
783void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
784 AutoMutex _l(mLock);
785
786 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
787 if (deviceIndex >= 0) {
788 InputDevice* device = mDevices.valueAt(deviceIndex);
789 device->cancelVibrate(token);
790 }
791}
792
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700793bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
794 AutoMutex _l(mLock);
795
796 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
797 if (deviceIndex >= 0) {
798 InputDevice* device = mDevices.valueAt(deviceIndex);
799 return device->isEnabled();
800 }
801 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
802 return false;
803}
804
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800805void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 AutoMutex _l(mLock);
807
808 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800809 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800811 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812
813 for (size_t i = 0; i < mDevices.size(); i++) {
814 mDevices.valueAt(i)->dump(dump);
815 }
816
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800817 dump += INDENT "Configuration:\n";
818 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
820 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800821 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100823 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800825 dump += "]\n";
826 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 mConfig.virtualKeyQuietTime * 0.000001f);
828
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800829 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
831 mConfig.pointerVelocityControlParameters.scale,
832 mConfig.pointerVelocityControlParameters.lowThreshold,
833 mConfig.pointerVelocityControlParameters.highThreshold,
834 mConfig.pointerVelocityControlParameters.acceleration);
835
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800836 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
838 mConfig.wheelVelocityControlParameters.scale,
839 mConfig.wheelVelocityControlParameters.lowThreshold,
840 mConfig.wheelVelocityControlParameters.highThreshold,
841 mConfig.wheelVelocityControlParameters.acceleration);
842
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800843 dump += StringPrintf(INDENT2 "PointerGesture:\n");
844 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800848 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800854 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800860 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800862 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800864 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800866 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700868
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800869 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700870 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871}
872
873void InputReader::monitor() {
874 // Acquire and release the lock to ensure that the reader has not deadlocked.
875 mLock.lock();
876 mEventHub->wake();
877 mReaderIsAliveCondition.wait(mLock);
878 mLock.unlock();
879
880 // Check the EventHub
881 mEventHub->monitor();
882}
883
884
885// --- InputReader::ContextImpl ---
886
887InputReader::ContextImpl::ContextImpl(InputReader* reader) :
888 mReader(reader) {
889}
890
891void InputReader::ContextImpl::updateGlobalMetaState() {
892 // lock is already held by the input loop
893 mReader->updateGlobalMetaStateLocked();
894}
895
896int32_t InputReader::ContextImpl::getGlobalMetaState() {
897 // lock is already held by the input loop
898 return mReader->getGlobalMetaStateLocked();
899}
900
901void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
902 // lock is already held by the input loop
903 mReader->disableVirtualKeysUntilLocked(time);
904}
905
906bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
907 InputDevice* device, int32_t keyCode, int32_t scanCode) {
908 // lock is already held by the input loop
909 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
910}
911
912void InputReader::ContextImpl::fadePointer() {
913 // lock is already held by the input loop
914 mReader->fadePointerLocked();
915}
916
917void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
918 // lock is already held by the input loop
919 mReader->requestTimeoutAtTimeLocked(when);
920}
921
922int32_t InputReader::ContextImpl::bumpGeneration() {
923 // lock is already held by the input loop
924 return mReader->bumpGenerationLocked();
925}
926
Michael Wright842500e2015-03-13 17:32:02 -0700927void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
928 // lock is already held by whatever called refreshConfigurationLocked
929 mReader->getExternalStylusDevicesLocked(outDevices);
930}
931
932void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
933 mReader->dispatchExternalStylusState(state);
934}
935
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
937 return mReader->mPolicy.get();
938}
939
940InputListenerInterface* InputReader::ContextImpl::getListener() {
941 return mReader->mQueuedListener.get();
942}
943
944EventHubInterface* InputReader::ContextImpl::getEventHub() {
945 return mReader->mEventHub.get();
946}
947
Prabir Pradhan42611e02018-11-27 14:04:02 -0800948uint32_t InputReader::ContextImpl::getNextSequenceNum() {
949 return (mReader->mNextSequenceNum)++;
950}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951
Michael Wrightd02c5b62014-02-10 15:10:22 -0800952// --- InputDevice ---
953
954InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
955 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
956 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
957 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700958 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800959}
960
961InputDevice::~InputDevice() {
962 size_t numMappers = mMappers.size();
963 for (size_t i = 0; i < numMappers; i++) {
964 delete mMappers[i];
965 }
966 mMappers.clear();
967}
968
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700969bool InputDevice::isEnabled() {
970 return getEventHub()->isDeviceEnabled(mId);
971}
972
973void InputDevice::setEnabled(bool enabled, nsecs_t when) {
974 if (isEnabled() == enabled) {
975 return;
976 }
977
978 if (enabled) {
979 getEventHub()->enableDevice(mId);
980 reset(when);
981 } else {
982 reset(when);
983 getEventHub()->disableDevice(mId);
984 }
985 // Must change generation to flag this device as changed
986 bumpGeneration();
987}
988
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800989void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800990 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700991 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800993 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100994 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800995 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
996 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -0700997 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
998 if (mAssociatedDisplayPort) {
999 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1000 } else {
1001 dump += "<none>\n";
1002 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001003 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1004 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1005 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001006
1007 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1008 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001009 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001010 for (size_t i = 0; i < ranges.size(); i++) {
1011 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1012 const char* label = getAxisLabel(range.axis);
1013 char name[32];
1014 if (label) {
1015 strncpy(name, label, sizeof(name));
1016 name[sizeof(name) - 1] = '\0';
1017 } else {
1018 snprintf(name, sizeof(name), "%d", range.axis);
1019 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001020 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001021 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1022 name, range.source, range.min, range.max, range.flat, range.fuzz,
1023 range.resolution);
1024 }
1025 }
1026
1027 size_t numMappers = mMappers.size();
1028 for (size_t i = 0; i < numMappers; i++) {
1029 InputMapper* mapper = mMappers[i];
1030 mapper->dump(dump);
1031 }
1032}
1033
1034void InputDevice::addMapper(InputMapper* mapper) {
1035 mMappers.add(mapper);
1036}
1037
1038void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1039 mSources = 0;
1040
1041 if (!isIgnored()) {
1042 if (!changes) { // first time only
1043 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1044 }
1045
1046 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1047 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1048 sp<KeyCharacterMap> keyboardLayout =
1049 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1050 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1051 bumpGeneration();
1052 }
1053 }
1054 }
1055
1056 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1057 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001058 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001059 if (mAlias != alias) {
1060 mAlias = alias;
1061 bumpGeneration();
1062 }
1063 }
1064 }
1065
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001066 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1067 ssize_t index = config->disabledDevices.indexOf(mId);
1068 bool enabled = index < 0;
1069 setEnabled(enabled, when);
1070 }
1071
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001072 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1073 // In most situations, no port will be specified.
1074 mAssociatedDisplayPort = std::nullopt;
1075 // Find the display port that corresponds to the current input port.
1076 const std::string& inputPort = mIdentifier.location;
1077 if (!inputPort.empty()) {
1078 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1079 const auto& displayPort = ports.find(inputPort);
1080 if (displayPort != ports.end()) {
1081 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1082 }
1083 }
1084 }
1085
Michael Wrightd02c5b62014-02-10 15:10:22 -08001086 size_t numMappers = mMappers.size();
1087 for (size_t i = 0; i < numMappers; i++) {
1088 InputMapper* mapper = mMappers[i];
1089 mapper->configure(when, config, changes);
1090 mSources |= mapper->getSources();
1091 }
1092 }
1093}
1094
1095void InputDevice::reset(nsecs_t when) {
1096 size_t numMappers = mMappers.size();
1097 for (size_t i = 0; i < numMappers; i++) {
1098 InputMapper* mapper = mMappers[i];
1099 mapper->reset(when);
1100 }
1101
1102 mContext->updateGlobalMetaState();
1103
1104 notifyReset(when);
1105}
1106
1107void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1108 // Process all of the events in order for each mapper.
1109 // We cannot simply ask each mapper to process them in bulk because mappers may
1110 // have side-effects that must be interleaved. For example, joystick movement events and
1111 // gamepad button presses are handled by different mappers but they should be dispatched
1112 // in the order received.
1113 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001114 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001115#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001116 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001117 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1118 rawEvent->when);
1119#endif
1120
1121 if (mDropUntilNextSync) {
1122 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1123 mDropUntilNextSync = false;
1124#if DEBUG_RAW_EVENTS
1125 ALOGD("Recovered from input event buffer overrun.");
1126#endif
1127 } else {
1128#if DEBUG_RAW_EVENTS
1129 ALOGD("Dropped input event while waiting for next input sync.");
1130#endif
1131 }
1132 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001133 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001134 mDropUntilNextSync = true;
1135 reset(rawEvent->when);
1136 } else {
1137 for (size_t i = 0; i < numMappers; i++) {
1138 InputMapper* mapper = mMappers[i];
1139 mapper->process(rawEvent);
1140 }
1141 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001142 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001143 }
1144}
1145
1146void InputDevice::timeoutExpired(nsecs_t when) {
1147 size_t numMappers = mMappers.size();
1148 for (size_t i = 0; i < numMappers; i++) {
1149 InputMapper* mapper = mMappers[i];
1150 mapper->timeoutExpired(when);
1151 }
1152}
1153
Michael Wright842500e2015-03-13 17:32:02 -07001154void InputDevice::updateExternalStylusState(const StylusState& state) {
1155 size_t numMappers = mMappers.size();
1156 for (size_t i = 0; i < numMappers; i++) {
1157 InputMapper* mapper = mMappers[i];
1158 mapper->updateExternalStylusState(state);
1159 }
1160}
1161
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1163 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001164 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 size_t numMappers = mMappers.size();
1166 for (size_t i = 0; i < numMappers; i++) {
1167 InputMapper* mapper = mMappers[i];
1168 mapper->populateDeviceInfo(outDeviceInfo);
1169 }
1170}
1171
1172int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1173 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1174}
1175
1176int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1177 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1178}
1179
1180int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1181 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1182}
1183
1184int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1185 int32_t result = AKEY_STATE_UNKNOWN;
1186 size_t numMappers = mMappers.size();
1187 for (size_t i = 0; i < numMappers; i++) {
1188 InputMapper* mapper = mMappers[i];
1189 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1190 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1191 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1192 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1193 if (currentResult >= AKEY_STATE_DOWN) {
1194 return currentResult;
1195 } else if (currentResult == AKEY_STATE_UP) {
1196 result = currentResult;
1197 }
1198 }
1199 }
1200 return result;
1201}
1202
1203bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1204 const int32_t* keyCodes, uint8_t* outFlags) {
1205 bool result = false;
1206 size_t numMappers = mMappers.size();
1207 for (size_t i = 0; i < numMappers; i++) {
1208 InputMapper* mapper = mMappers[i];
1209 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1210 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1211 }
1212 }
1213 return result;
1214}
1215
1216void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1217 int32_t token) {
1218 size_t numMappers = mMappers.size();
1219 for (size_t i = 0; i < numMappers; i++) {
1220 InputMapper* mapper = mMappers[i];
1221 mapper->vibrate(pattern, patternSize, repeat, token);
1222 }
1223}
1224
1225void InputDevice::cancelVibrate(int32_t token) {
1226 size_t numMappers = mMappers.size();
1227 for (size_t i = 0; i < numMappers; i++) {
1228 InputMapper* mapper = mMappers[i];
1229 mapper->cancelVibrate(token);
1230 }
1231}
1232
Jeff Brownc9aa6282015-02-11 19:03:28 -08001233void InputDevice::cancelTouch(nsecs_t when) {
1234 size_t numMappers = mMappers.size();
1235 for (size_t i = 0; i < numMappers; i++) {
1236 InputMapper* mapper = mMappers[i];
1237 mapper->cancelTouch(when);
1238 }
1239}
1240
Michael Wrightd02c5b62014-02-10 15:10:22 -08001241int32_t InputDevice::getMetaState() {
1242 int32_t result = 0;
1243 size_t numMappers = mMappers.size();
1244 for (size_t i = 0; i < numMappers; i++) {
1245 InputMapper* mapper = mMappers[i];
1246 result |= mapper->getMetaState();
1247 }
1248 return result;
1249}
1250
Andrii Kulian763a3a42016-03-08 10:46:16 -08001251void InputDevice::updateMetaState(int32_t keyCode) {
1252 size_t numMappers = mMappers.size();
1253 for (size_t i = 0; i < numMappers; i++) {
1254 mMappers[i]->updateMetaState(keyCode);
1255 }
1256}
1257
Michael Wrightd02c5b62014-02-10 15:10:22 -08001258void InputDevice::fadePointer() {
1259 size_t numMappers = mMappers.size();
1260 for (size_t i = 0; i < numMappers; i++) {
1261 InputMapper* mapper = mMappers[i];
1262 mapper->fadePointer();
1263 }
1264}
1265
1266void InputDevice::bumpGeneration() {
1267 mGeneration = mContext->bumpGeneration();
1268}
1269
1270void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001271 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 mContext->getListener()->notifyDeviceReset(&args);
1273}
1274
1275
1276// --- CursorButtonAccumulator ---
1277
1278CursorButtonAccumulator::CursorButtonAccumulator() {
1279 clearButtons();
1280}
1281
1282void CursorButtonAccumulator::reset(InputDevice* device) {
1283 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1284 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1285 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1286 mBtnBack = device->isKeyPressed(BTN_BACK);
1287 mBtnSide = device->isKeyPressed(BTN_SIDE);
1288 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1289 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1290 mBtnTask = device->isKeyPressed(BTN_TASK);
1291}
1292
1293void CursorButtonAccumulator::clearButtons() {
1294 mBtnLeft = 0;
1295 mBtnRight = 0;
1296 mBtnMiddle = 0;
1297 mBtnBack = 0;
1298 mBtnSide = 0;
1299 mBtnForward = 0;
1300 mBtnExtra = 0;
1301 mBtnTask = 0;
1302}
1303
1304void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1305 if (rawEvent->type == EV_KEY) {
1306 switch (rawEvent->code) {
1307 case BTN_LEFT:
1308 mBtnLeft = rawEvent->value;
1309 break;
1310 case BTN_RIGHT:
1311 mBtnRight = rawEvent->value;
1312 break;
1313 case BTN_MIDDLE:
1314 mBtnMiddle = rawEvent->value;
1315 break;
1316 case BTN_BACK:
1317 mBtnBack = rawEvent->value;
1318 break;
1319 case BTN_SIDE:
1320 mBtnSide = rawEvent->value;
1321 break;
1322 case BTN_FORWARD:
1323 mBtnForward = rawEvent->value;
1324 break;
1325 case BTN_EXTRA:
1326 mBtnExtra = rawEvent->value;
1327 break;
1328 case BTN_TASK:
1329 mBtnTask = rawEvent->value;
1330 break;
1331 }
1332 }
1333}
1334
1335uint32_t CursorButtonAccumulator::getButtonState() const {
1336 uint32_t result = 0;
1337 if (mBtnLeft) {
1338 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1339 }
1340 if (mBtnRight) {
1341 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1342 }
1343 if (mBtnMiddle) {
1344 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1345 }
1346 if (mBtnBack || mBtnSide) {
1347 result |= AMOTION_EVENT_BUTTON_BACK;
1348 }
1349 if (mBtnForward || mBtnExtra) {
1350 result |= AMOTION_EVENT_BUTTON_FORWARD;
1351 }
1352 return result;
1353}
1354
1355
1356// --- CursorMotionAccumulator ---
1357
1358CursorMotionAccumulator::CursorMotionAccumulator() {
1359 clearRelativeAxes();
1360}
1361
1362void CursorMotionAccumulator::reset(InputDevice* device) {
1363 clearRelativeAxes();
1364}
1365
1366void CursorMotionAccumulator::clearRelativeAxes() {
1367 mRelX = 0;
1368 mRelY = 0;
1369}
1370
1371void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1372 if (rawEvent->type == EV_REL) {
1373 switch (rawEvent->code) {
1374 case REL_X:
1375 mRelX = rawEvent->value;
1376 break;
1377 case REL_Y:
1378 mRelY = rawEvent->value;
1379 break;
1380 }
1381 }
1382}
1383
1384void CursorMotionAccumulator::finishSync() {
1385 clearRelativeAxes();
1386}
1387
1388
1389// --- CursorScrollAccumulator ---
1390
1391CursorScrollAccumulator::CursorScrollAccumulator() :
1392 mHaveRelWheel(false), mHaveRelHWheel(false) {
1393 clearRelativeAxes();
1394}
1395
1396void CursorScrollAccumulator::configure(InputDevice* device) {
1397 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1398 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1399}
1400
1401void CursorScrollAccumulator::reset(InputDevice* device) {
1402 clearRelativeAxes();
1403}
1404
1405void CursorScrollAccumulator::clearRelativeAxes() {
1406 mRelWheel = 0;
1407 mRelHWheel = 0;
1408}
1409
1410void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1411 if (rawEvent->type == EV_REL) {
1412 switch (rawEvent->code) {
1413 case REL_WHEEL:
1414 mRelWheel = rawEvent->value;
1415 break;
1416 case REL_HWHEEL:
1417 mRelHWheel = rawEvent->value;
1418 break;
1419 }
1420 }
1421}
1422
1423void CursorScrollAccumulator::finishSync() {
1424 clearRelativeAxes();
1425}
1426
1427
1428// --- TouchButtonAccumulator ---
1429
1430TouchButtonAccumulator::TouchButtonAccumulator() :
1431 mHaveBtnTouch(false), mHaveStylus(false) {
1432 clearButtons();
1433}
1434
1435void TouchButtonAccumulator::configure(InputDevice* device) {
1436 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1437 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1438 || device->hasKey(BTN_TOOL_RUBBER)
1439 || device->hasKey(BTN_TOOL_BRUSH)
1440 || device->hasKey(BTN_TOOL_PENCIL)
1441 || device->hasKey(BTN_TOOL_AIRBRUSH);
1442}
1443
1444void TouchButtonAccumulator::reset(InputDevice* device) {
1445 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1446 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001447 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1448 mBtnStylus2 =
1449 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001450 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1451 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1452 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1453 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1454 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1455 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1456 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1457 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1458 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1459 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1460 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1461}
1462
1463void TouchButtonAccumulator::clearButtons() {
1464 mBtnTouch = 0;
1465 mBtnStylus = 0;
1466 mBtnStylus2 = 0;
1467 mBtnToolFinger = 0;
1468 mBtnToolPen = 0;
1469 mBtnToolRubber = 0;
1470 mBtnToolBrush = 0;
1471 mBtnToolPencil = 0;
1472 mBtnToolAirbrush = 0;
1473 mBtnToolMouse = 0;
1474 mBtnToolLens = 0;
1475 mBtnToolDoubleTap = 0;
1476 mBtnToolTripleTap = 0;
1477 mBtnToolQuadTap = 0;
1478}
1479
1480void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1481 if (rawEvent->type == EV_KEY) {
1482 switch (rawEvent->code) {
1483 case BTN_TOUCH:
1484 mBtnTouch = rawEvent->value;
1485 break;
1486 case BTN_STYLUS:
1487 mBtnStylus = rawEvent->value;
1488 break;
1489 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001490 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001491 mBtnStylus2 = rawEvent->value;
1492 break;
1493 case BTN_TOOL_FINGER:
1494 mBtnToolFinger = rawEvent->value;
1495 break;
1496 case BTN_TOOL_PEN:
1497 mBtnToolPen = rawEvent->value;
1498 break;
1499 case BTN_TOOL_RUBBER:
1500 mBtnToolRubber = rawEvent->value;
1501 break;
1502 case BTN_TOOL_BRUSH:
1503 mBtnToolBrush = rawEvent->value;
1504 break;
1505 case BTN_TOOL_PENCIL:
1506 mBtnToolPencil = rawEvent->value;
1507 break;
1508 case BTN_TOOL_AIRBRUSH:
1509 mBtnToolAirbrush = rawEvent->value;
1510 break;
1511 case BTN_TOOL_MOUSE:
1512 mBtnToolMouse = rawEvent->value;
1513 break;
1514 case BTN_TOOL_LENS:
1515 mBtnToolLens = rawEvent->value;
1516 break;
1517 case BTN_TOOL_DOUBLETAP:
1518 mBtnToolDoubleTap = rawEvent->value;
1519 break;
1520 case BTN_TOOL_TRIPLETAP:
1521 mBtnToolTripleTap = rawEvent->value;
1522 break;
1523 case BTN_TOOL_QUADTAP:
1524 mBtnToolQuadTap = rawEvent->value;
1525 break;
1526 }
1527 }
1528}
1529
1530uint32_t TouchButtonAccumulator::getButtonState() const {
1531 uint32_t result = 0;
1532 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001533 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 }
1535 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001536 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001537 }
1538 return result;
1539}
1540
1541int32_t TouchButtonAccumulator::getToolType() const {
1542 if (mBtnToolMouse || mBtnToolLens) {
1543 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1544 }
1545 if (mBtnToolRubber) {
1546 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1547 }
1548 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1549 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1550 }
1551 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1552 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1553 }
1554 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1555}
1556
1557bool TouchButtonAccumulator::isToolActive() const {
1558 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1559 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1560 || mBtnToolMouse || mBtnToolLens
1561 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1562}
1563
1564bool TouchButtonAccumulator::isHovering() const {
1565 return mHaveBtnTouch && !mBtnTouch;
1566}
1567
1568bool TouchButtonAccumulator::hasStylus() const {
1569 return mHaveStylus;
1570}
1571
1572
1573// --- RawPointerAxes ---
1574
1575RawPointerAxes::RawPointerAxes() {
1576 clear();
1577}
1578
1579void RawPointerAxes::clear() {
1580 x.clear();
1581 y.clear();
1582 pressure.clear();
1583 touchMajor.clear();
1584 touchMinor.clear();
1585 toolMajor.clear();
1586 toolMinor.clear();
1587 orientation.clear();
1588 distance.clear();
1589 tiltX.clear();
1590 tiltY.clear();
1591 trackingId.clear();
1592 slot.clear();
1593}
1594
1595
1596// --- RawPointerData ---
1597
1598RawPointerData::RawPointerData() {
1599 clear();
1600}
1601
1602void RawPointerData::clear() {
1603 pointerCount = 0;
1604 clearIdBits();
1605}
1606
1607void RawPointerData::copyFrom(const RawPointerData& other) {
1608 pointerCount = other.pointerCount;
1609 hoveringIdBits = other.hoveringIdBits;
1610 touchingIdBits = other.touchingIdBits;
1611
1612 for (uint32_t i = 0; i < pointerCount; i++) {
1613 pointers[i] = other.pointers[i];
1614
1615 int id = pointers[i].id;
1616 idToIndex[id] = other.idToIndex[id];
1617 }
1618}
1619
1620void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1621 float x = 0, y = 0;
1622 uint32_t count = touchingIdBits.count();
1623 if (count) {
1624 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1625 uint32_t id = idBits.clearFirstMarkedBit();
1626 const Pointer& pointer = pointerForId(id);
1627 x += pointer.x;
1628 y += pointer.y;
1629 }
1630 x /= count;
1631 y /= count;
1632 }
1633 *outX = x;
1634 *outY = y;
1635}
1636
1637
1638// --- CookedPointerData ---
1639
1640CookedPointerData::CookedPointerData() {
1641 clear();
1642}
1643
1644void CookedPointerData::clear() {
1645 pointerCount = 0;
1646 hoveringIdBits.clear();
1647 touchingIdBits.clear();
1648}
1649
1650void CookedPointerData::copyFrom(const CookedPointerData& other) {
1651 pointerCount = other.pointerCount;
1652 hoveringIdBits = other.hoveringIdBits;
1653 touchingIdBits = other.touchingIdBits;
1654
1655 for (uint32_t i = 0; i < pointerCount; i++) {
1656 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1657 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1658
1659 int id = pointerProperties[i].id;
1660 idToIndex[id] = other.idToIndex[id];
1661 }
1662}
1663
1664
1665// --- SingleTouchMotionAccumulator ---
1666
1667SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1668 clearAbsoluteAxes();
1669}
1670
1671void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1672 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1673 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1674 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1675 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1676 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1677 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1678 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1679}
1680
1681void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1682 mAbsX = 0;
1683 mAbsY = 0;
1684 mAbsPressure = 0;
1685 mAbsToolWidth = 0;
1686 mAbsDistance = 0;
1687 mAbsTiltX = 0;
1688 mAbsTiltY = 0;
1689}
1690
1691void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1692 if (rawEvent->type == EV_ABS) {
1693 switch (rawEvent->code) {
1694 case ABS_X:
1695 mAbsX = rawEvent->value;
1696 break;
1697 case ABS_Y:
1698 mAbsY = rawEvent->value;
1699 break;
1700 case ABS_PRESSURE:
1701 mAbsPressure = rawEvent->value;
1702 break;
1703 case ABS_TOOL_WIDTH:
1704 mAbsToolWidth = rawEvent->value;
1705 break;
1706 case ABS_DISTANCE:
1707 mAbsDistance = rawEvent->value;
1708 break;
1709 case ABS_TILT_X:
1710 mAbsTiltX = rawEvent->value;
1711 break;
1712 case ABS_TILT_Y:
1713 mAbsTiltY = rawEvent->value;
1714 break;
1715 }
1716 }
1717}
1718
1719
1720// --- MultiTouchMotionAccumulator ---
1721
1722MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001723 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001724 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001725}
1726
1727MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1728 delete[] mSlots;
1729}
1730
1731void MultiTouchMotionAccumulator::configure(InputDevice* device,
1732 size_t slotCount, bool usingSlotsProtocol) {
1733 mSlotCount = slotCount;
1734 mUsingSlotsProtocol = usingSlotsProtocol;
1735 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1736
1737 delete[] mSlots;
1738 mSlots = new Slot[slotCount];
1739}
1740
1741void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1742 // Unfortunately there is no way to read the initial contents of the slots.
1743 // So when we reset the accumulator, we must assume they are all zeroes.
1744 if (mUsingSlotsProtocol) {
1745 // Query the driver for the current slot index and use it as the initial slot
1746 // before we start reading events from the device. It is possible that the
1747 // current slot index will not be the same as it was when the first event was
1748 // written into the evdev buffer, which means the input mapper could start
1749 // out of sync with the initial state of the events in the evdev buffer.
1750 // In the extremely unlikely case that this happens, the data from
1751 // two slots will be confused until the next ABS_MT_SLOT event is received.
1752 // This can cause the touch point to "jump", but at least there will be
1753 // no stuck touches.
1754 int32_t initialSlot;
1755 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1756 ABS_MT_SLOT, &initialSlot);
1757 if (status) {
1758 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1759 initialSlot = -1;
1760 }
1761 clearSlots(initialSlot);
1762 } else {
1763 clearSlots(-1);
1764 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001765 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001766}
1767
1768void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1769 if (mSlots) {
1770 for (size_t i = 0; i < mSlotCount; i++) {
1771 mSlots[i].clear();
1772 }
1773 }
1774 mCurrentSlot = initialSlot;
1775}
1776
1777void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1778 if (rawEvent->type == EV_ABS) {
1779 bool newSlot = false;
1780 if (mUsingSlotsProtocol) {
1781 if (rawEvent->code == ABS_MT_SLOT) {
1782 mCurrentSlot = rawEvent->value;
1783 newSlot = true;
1784 }
1785 } else if (mCurrentSlot < 0) {
1786 mCurrentSlot = 0;
1787 }
1788
1789 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1790#if DEBUG_POINTERS
1791 if (newSlot) {
1792 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001793 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001794 mCurrentSlot, mSlotCount - 1);
1795 }
1796#endif
1797 } else {
1798 Slot* slot = &mSlots[mCurrentSlot];
1799
1800 switch (rawEvent->code) {
1801 case ABS_MT_POSITION_X:
1802 slot->mInUse = true;
1803 slot->mAbsMTPositionX = rawEvent->value;
1804 break;
1805 case ABS_MT_POSITION_Y:
1806 slot->mInUse = true;
1807 slot->mAbsMTPositionY = rawEvent->value;
1808 break;
1809 case ABS_MT_TOUCH_MAJOR:
1810 slot->mInUse = true;
1811 slot->mAbsMTTouchMajor = rawEvent->value;
1812 break;
1813 case ABS_MT_TOUCH_MINOR:
1814 slot->mInUse = true;
1815 slot->mAbsMTTouchMinor = rawEvent->value;
1816 slot->mHaveAbsMTTouchMinor = true;
1817 break;
1818 case ABS_MT_WIDTH_MAJOR:
1819 slot->mInUse = true;
1820 slot->mAbsMTWidthMajor = rawEvent->value;
1821 break;
1822 case ABS_MT_WIDTH_MINOR:
1823 slot->mInUse = true;
1824 slot->mAbsMTWidthMinor = rawEvent->value;
1825 slot->mHaveAbsMTWidthMinor = true;
1826 break;
1827 case ABS_MT_ORIENTATION:
1828 slot->mInUse = true;
1829 slot->mAbsMTOrientation = rawEvent->value;
1830 break;
1831 case ABS_MT_TRACKING_ID:
1832 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1833 // The slot is no longer in use but it retains its previous contents,
1834 // which may be reused for subsequent touches.
1835 slot->mInUse = false;
1836 } else {
1837 slot->mInUse = true;
1838 slot->mAbsMTTrackingId = rawEvent->value;
1839 }
1840 break;
1841 case ABS_MT_PRESSURE:
1842 slot->mInUse = true;
1843 slot->mAbsMTPressure = rawEvent->value;
1844 break;
1845 case ABS_MT_DISTANCE:
1846 slot->mInUse = true;
1847 slot->mAbsMTDistance = rawEvent->value;
1848 break;
1849 case ABS_MT_TOOL_TYPE:
1850 slot->mInUse = true;
1851 slot->mAbsMTToolType = rawEvent->value;
1852 slot->mHaveAbsMTToolType = true;
1853 break;
1854 }
1855 }
1856 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1857 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1858 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001859 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1860 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001861 }
1862}
1863
1864void MultiTouchMotionAccumulator::finishSync() {
1865 if (!mUsingSlotsProtocol) {
1866 clearSlots(-1);
1867 }
1868}
1869
1870bool MultiTouchMotionAccumulator::hasStylus() const {
1871 return mHaveStylus;
1872}
1873
1874
1875// --- MultiTouchMotionAccumulator::Slot ---
1876
1877MultiTouchMotionAccumulator::Slot::Slot() {
1878 clear();
1879}
1880
1881void MultiTouchMotionAccumulator::Slot::clear() {
1882 mInUse = false;
1883 mHaveAbsMTTouchMinor = false;
1884 mHaveAbsMTWidthMinor = false;
1885 mHaveAbsMTToolType = false;
1886 mAbsMTPositionX = 0;
1887 mAbsMTPositionY = 0;
1888 mAbsMTTouchMajor = 0;
1889 mAbsMTTouchMinor = 0;
1890 mAbsMTWidthMajor = 0;
1891 mAbsMTWidthMinor = 0;
1892 mAbsMTOrientation = 0;
1893 mAbsMTTrackingId = -1;
1894 mAbsMTPressure = 0;
1895 mAbsMTDistance = 0;
1896 mAbsMTToolType = 0;
1897}
1898
1899int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1900 if (mHaveAbsMTToolType) {
1901 switch (mAbsMTToolType) {
1902 case MT_TOOL_FINGER:
1903 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1904 case MT_TOOL_PEN:
1905 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1906 }
1907 }
1908 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1909}
1910
1911
1912// --- InputMapper ---
1913
1914InputMapper::InputMapper(InputDevice* device) :
1915 mDevice(device), mContext(device->getContext()) {
1916}
1917
1918InputMapper::~InputMapper() {
1919}
1920
1921void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1922 info->addSource(getSources());
1923}
1924
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001925void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001926}
1927
1928void InputMapper::configure(nsecs_t when,
1929 const InputReaderConfiguration* config, uint32_t changes) {
1930}
1931
1932void InputMapper::reset(nsecs_t when) {
1933}
1934
1935void InputMapper::timeoutExpired(nsecs_t when) {
1936}
1937
1938int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1939 return AKEY_STATE_UNKNOWN;
1940}
1941
1942int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1943 return AKEY_STATE_UNKNOWN;
1944}
1945
1946int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1947 return AKEY_STATE_UNKNOWN;
1948}
1949
1950bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1951 const int32_t* keyCodes, uint8_t* outFlags) {
1952 return false;
1953}
1954
1955void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1956 int32_t token) {
1957}
1958
1959void InputMapper::cancelVibrate(int32_t token) {
1960}
1961
Jeff Brownc9aa6282015-02-11 19:03:28 -08001962void InputMapper::cancelTouch(nsecs_t when) {
1963}
1964
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965int32_t InputMapper::getMetaState() {
1966 return 0;
1967}
1968
Andrii Kulian763a3a42016-03-08 10:46:16 -08001969void InputMapper::updateMetaState(int32_t keyCode) {
1970}
1971
Michael Wright842500e2015-03-13 17:32:02 -07001972void InputMapper::updateExternalStylusState(const StylusState& state) {
1973
1974}
1975
Michael Wrightd02c5b62014-02-10 15:10:22 -08001976void InputMapper::fadePointer() {
1977}
1978
1979status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1980 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1981}
1982
1983void InputMapper::bumpGeneration() {
1984 mDevice->bumpGeneration();
1985}
1986
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001987void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 const RawAbsoluteAxisInfo& axis, const char* name) {
1989 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001990 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1992 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001993 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994 }
1995}
1996
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001997void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1998 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1999 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2000 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2001 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002002}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002003
2004// --- SwitchInputMapper ---
2005
2006SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002007 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002008}
2009
2010SwitchInputMapper::~SwitchInputMapper() {
2011}
2012
2013uint32_t SwitchInputMapper::getSources() {
2014 return AINPUT_SOURCE_SWITCH;
2015}
2016
2017void SwitchInputMapper::process(const RawEvent* rawEvent) {
2018 switch (rawEvent->type) {
2019 case EV_SW:
2020 processSwitch(rawEvent->code, rawEvent->value);
2021 break;
2022
2023 case EV_SYN:
2024 if (rawEvent->code == SYN_REPORT) {
2025 sync(rawEvent->when);
2026 }
2027 }
2028}
2029
2030void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2031 if (switchCode >= 0 && switchCode < 32) {
2032 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002033 mSwitchValues |= 1 << switchCode;
2034 } else {
2035 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036 }
2037 mUpdatedSwitchMask |= 1 << switchCode;
2038 }
2039}
2040
2041void SwitchInputMapper::sync(nsecs_t when) {
2042 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002043 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002044 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2045 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002046 getListener()->notifySwitch(&args);
2047
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048 mUpdatedSwitchMask = 0;
2049 }
2050}
2051
2052int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2053 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2054}
2055
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002056void SwitchInputMapper::dump(std::string& dump) {
2057 dump += INDENT2 "Switch Input Mapper:\n";
2058 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002059}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002060
2061// --- VibratorInputMapper ---
2062
2063VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2064 InputMapper(device), mVibrating(false) {
2065}
2066
2067VibratorInputMapper::~VibratorInputMapper() {
2068}
2069
2070uint32_t VibratorInputMapper::getSources() {
2071 return 0;
2072}
2073
2074void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2075 InputMapper::populateDeviceInfo(info);
2076
2077 info->setVibrator(true);
2078}
2079
2080void VibratorInputMapper::process(const RawEvent* rawEvent) {
2081 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2082}
2083
2084void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2085 int32_t token) {
2086#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002087 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002088 for (size_t i = 0; i < patternSize; i++) {
2089 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002090 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002092 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002094 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002095 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002096#endif
2097
2098 mVibrating = true;
2099 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2100 mPatternSize = patternSize;
2101 mRepeat = repeat;
2102 mToken = token;
2103 mIndex = -1;
2104
2105 nextStep();
2106}
2107
2108void VibratorInputMapper::cancelVibrate(int32_t token) {
2109#if DEBUG_VIBRATOR
2110 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2111#endif
2112
2113 if (mVibrating && mToken == token) {
2114 stopVibrating();
2115 }
2116}
2117
2118void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2119 if (mVibrating) {
2120 if (when >= mNextStepTime) {
2121 nextStep();
2122 } else {
2123 getContext()->requestTimeoutAtTime(mNextStepTime);
2124 }
2125 }
2126}
2127
2128void VibratorInputMapper::nextStep() {
2129 mIndex += 1;
2130 if (size_t(mIndex) >= mPatternSize) {
2131 if (mRepeat < 0) {
2132 // We are done.
2133 stopVibrating();
2134 return;
2135 }
2136 mIndex = mRepeat;
2137 }
2138
2139 bool vibratorOn = mIndex & 1;
2140 nsecs_t duration = mPattern[mIndex];
2141 if (vibratorOn) {
2142#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002143 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002144#endif
2145 getEventHub()->vibrate(getDeviceId(), duration);
2146 } else {
2147#if DEBUG_VIBRATOR
2148 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2149#endif
2150 getEventHub()->cancelVibrate(getDeviceId());
2151 }
2152 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2153 mNextStepTime = now + duration;
2154 getContext()->requestTimeoutAtTime(mNextStepTime);
2155#if DEBUG_VIBRATOR
2156 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2157#endif
2158}
2159
2160void VibratorInputMapper::stopVibrating() {
2161 mVibrating = false;
2162#if DEBUG_VIBRATOR
2163 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2164#endif
2165 getEventHub()->cancelVibrate(getDeviceId());
2166}
2167
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002168void VibratorInputMapper::dump(std::string& dump) {
2169 dump += INDENT2 "Vibrator Input Mapper:\n";
2170 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002171}
2172
2173
2174// --- KeyboardInputMapper ---
2175
2176KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2177 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002178 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002179}
2180
2181KeyboardInputMapper::~KeyboardInputMapper() {
2182}
2183
2184uint32_t KeyboardInputMapper::getSources() {
2185 return mSource;
2186}
2187
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002188int32_t KeyboardInputMapper::getOrientation() {
2189 if (mViewport) {
2190 return mViewport->orientation;
2191 }
2192 return DISPLAY_ORIENTATION_0;
2193}
2194
2195int32_t KeyboardInputMapper::getDisplayId() {
2196 if (mViewport) {
2197 return mViewport->displayId;
2198 }
2199 return ADISPLAY_ID_NONE;
2200}
2201
Michael Wrightd02c5b62014-02-10 15:10:22 -08002202void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2203 InputMapper::populateDeviceInfo(info);
2204
2205 info->setKeyboardType(mKeyboardType);
2206 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2207}
2208
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002209void KeyboardInputMapper::dump(std::string& dump) {
2210 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002211 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002212 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002213 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002214 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2215 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2216 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002217}
2218
Michael Wrightd02c5b62014-02-10 15:10:22 -08002219void KeyboardInputMapper::configure(nsecs_t when,
2220 const InputReaderConfiguration* config, uint32_t changes) {
2221 InputMapper::configure(when, config, changes);
2222
2223 if (!changes) { // first time only
2224 // Configure basic parameters.
2225 configureParameters();
2226 }
2227
2228 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002229 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002230 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 }
2232 }
2233}
2234
Ivan Podogovb9afef32017-02-13 15:34:32 +00002235static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2236 int32_t mapped = 0;
2237 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2238 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2239 if (stemKeyRotationMap[i][0] == keyCode) {
2240 stemKeyRotationMap[i][1] = mapped;
2241 return;
2242 }
2243 }
2244 }
2245}
2246
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247void KeyboardInputMapper::configureParameters() {
2248 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002249 const PropertyMap& config = getDevice()->getConfiguration();
2250 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002251 mParameters.orientationAware);
2252
Michael Wrightd02c5b62014-02-10 15:10:22 -08002253 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002254 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2255 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2256 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2257 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002258 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002259
2260 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002261 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002262 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002263}
2264
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002265void KeyboardInputMapper::dumpParameters(std::string& dump) {
2266 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002267 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002268 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002269 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002270 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002271}
2272
2273void KeyboardInputMapper::reset(nsecs_t when) {
2274 mMetaState = AMETA_NONE;
2275 mDownTime = 0;
2276 mKeyDowns.clear();
2277 mCurrentHidUsage = 0;
2278
2279 resetLedState();
2280
2281 InputMapper::reset(when);
2282}
2283
2284void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2285 switch (rawEvent->type) {
2286 case EV_KEY: {
2287 int32_t scanCode = rawEvent->code;
2288 int32_t usageCode = mCurrentHidUsage;
2289 mCurrentHidUsage = 0;
2290
2291 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002292 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002293 }
2294 break;
2295 }
2296 case EV_MSC: {
2297 if (rawEvent->code == MSC_SCAN) {
2298 mCurrentHidUsage = rawEvent->value;
2299 }
2300 break;
2301 }
2302 case EV_SYN: {
2303 if (rawEvent->code == SYN_REPORT) {
2304 mCurrentHidUsage = 0;
2305 }
2306 }
2307 }
2308}
2309
2310bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2311 return scanCode < BTN_MOUSE
2312 || scanCode >= KEY_OK
2313 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2314 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2315}
2316
Michael Wright58ba9882017-07-26 16:19:11 +01002317bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2318 switch (keyCode) {
2319 case AKEYCODE_MEDIA_PLAY:
2320 case AKEYCODE_MEDIA_PAUSE:
2321 case AKEYCODE_MEDIA_PLAY_PAUSE:
2322 case AKEYCODE_MUTE:
2323 case AKEYCODE_HEADSETHOOK:
2324 case AKEYCODE_MEDIA_STOP:
2325 case AKEYCODE_MEDIA_NEXT:
2326 case AKEYCODE_MEDIA_PREVIOUS:
2327 case AKEYCODE_MEDIA_REWIND:
2328 case AKEYCODE_MEDIA_RECORD:
2329 case AKEYCODE_MEDIA_FAST_FORWARD:
2330 case AKEYCODE_MEDIA_SKIP_FORWARD:
2331 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2332 case AKEYCODE_MEDIA_STEP_FORWARD:
2333 case AKEYCODE_MEDIA_STEP_BACKWARD:
2334 case AKEYCODE_MEDIA_AUDIO_TRACK:
2335 case AKEYCODE_VOLUME_UP:
2336 case AKEYCODE_VOLUME_DOWN:
2337 case AKEYCODE_VOLUME_MUTE:
2338 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2339 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2340 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2341 return true;
2342 }
2343 return false;
2344}
2345
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002346void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2347 int32_t usageCode) {
2348 int32_t keyCode;
2349 int32_t keyMetaState;
2350 uint32_t policyFlags;
2351
2352 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2353 &keyCode, &keyMetaState, &policyFlags)) {
2354 keyCode = AKEYCODE_UNKNOWN;
2355 keyMetaState = mMetaState;
2356 policyFlags = 0;
2357 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002358
2359 if (down) {
2360 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002361 if (mParameters.orientationAware) {
2362 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002363 }
2364
2365 // Add key down.
2366 ssize_t keyDownIndex = findKeyDown(scanCode);
2367 if (keyDownIndex >= 0) {
2368 // key repeat, be sure to use same keycode as before in case of rotation
2369 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2370 } else {
2371 // key down
2372 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2373 && mContext->shouldDropVirtualKey(when,
2374 getDevice(), keyCode, scanCode)) {
2375 return;
2376 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002377 if (policyFlags & POLICY_FLAG_GESTURE) {
2378 mDevice->cancelTouch(when);
2379 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002380
2381 mKeyDowns.push();
2382 KeyDown& keyDown = mKeyDowns.editTop();
2383 keyDown.keyCode = keyCode;
2384 keyDown.scanCode = scanCode;
2385 }
2386
2387 mDownTime = when;
2388 } else {
2389 // Remove key down.
2390 ssize_t keyDownIndex = findKeyDown(scanCode);
2391 if (keyDownIndex >= 0) {
2392 // key up, be sure to use same keycode as before in case of rotation
2393 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2394 mKeyDowns.removeAt(size_t(keyDownIndex));
2395 } else {
2396 // key was not actually down
2397 ALOGI("Dropping key up from device %s because the key was not down. "
2398 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002399 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002400 return;
2401 }
2402 }
2403
Andrii Kulian763a3a42016-03-08 10:46:16 -08002404 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002405 // If global meta state changed send it along with the key.
2406 // If it has not changed then we'll use what keymap gave us,
2407 // since key replacement logic might temporarily reset a few
2408 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002409 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002410 }
2411
2412 nsecs_t downTime = mDownTime;
2413
2414 // Key down on external an keyboard should wake the device.
2415 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2416 // For internal keyboards, the key layout file should specify the policy flags for
2417 // each wake key individually.
2418 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002419 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002420 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002421 }
2422
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002423 if (mParameters.handlesKeyRepeat) {
2424 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2425 }
2426
Prabir Pradhan42611e02018-11-27 14:04:02 -08002427 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2428 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002429 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002430 getListener()->notifyKey(&args);
2431}
2432
2433ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2434 size_t n = mKeyDowns.size();
2435 for (size_t i = 0; i < n; i++) {
2436 if (mKeyDowns[i].scanCode == scanCode) {
2437 return i;
2438 }
2439 }
2440 return -1;
2441}
2442
2443int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2444 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2445}
2446
2447int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2448 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2449}
2450
2451bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2452 const int32_t* keyCodes, uint8_t* outFlags) {
2453 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2454}
2455
2456int32_t KeyboardInputMapper::getMetaState() {
2457 return mMetaState;
2458}
2459
Andrii Kulian763a3a42016-03-08 10:46:16 -08002460void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2461 updateMetaStateIfNeeded(keyCode, false);
2462}
2463
2464bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2465 int32_t oldMetaState = mMetaState;
2466 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2467 bool metaStateChanged = oldMetaState != newMetaState;
2468 if (metaStateChanged) {
2469 mMetaState = newMetaState;
2470 updateLedState(false);
2471
2472 getContext()->updateGlobalMetaState();
2473 }
2474
2475 return metaStateChanged;
2476}
2477
Michael Wrightd02c5b62014-02-10 15:10:22 -08002478void KeyboardInputMapper::resetLedState() {
2479 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2480 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2481 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2482
2483 updateLedState(true);
2484}
2485
2486void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2487 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2488 ledState.on = false;
2489}
2490
2491void KeyboardInputMapper::updateLedState(bool reset) {
2492 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2493 AMETA_CAPS_LOCK_ON, reset);
2494 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2495 AMETA_NUM_LOCK_ON, reset);
2496 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2497 AMETA_SCROLL_LOCK_ON, reset);
2498}
2499
2500void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2501 int32_t led, int32_t modifier, bool reset) {
2502 if (ledState.avail) {
2503 bool desiredState = (mMetaState & modifier) != 0;
2504 if (reset || ledState.on != desiredState) {
2505 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2506 ledState.on = desiredState;
2507 }
2508 }
2509}
2510
2511
2512// --- CursorInputMapper ---
2513
2514CursorInputMapper::CursorInputMapper(InputDevice* device) :
2515 InputMapper(device) {
2516}
2517
2518CursorInputMapper::~CursorInputMapper() {
2519}
2520
2521uint32_t CursorInputMapper::getSources() {
2522 return mSource;
2523}
2524
2525void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2526 InputMapper::populateDeviceInfo(info);
2527
2528 if (mParameters.mode == Parameters::MODE_POINTER) {
2529 float minX, minY, maxX, maxY;
2530 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2531 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2532 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2533 }
2534 } else {
2535 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2536 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2537 }
2538 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2539
2540 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2541 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2542 }
2543 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2544 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2545 }
2546}
2547
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002548void CursorInputMapper::dump(std::string& dump) {
2549 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002550 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002551 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2552 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2553 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2554 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2555 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002556 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002557 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002558 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002559 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2560 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2561 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2562 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2563 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2564 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002565}
2566
2567void CursorInputMapper::configure(nsecs_t when,
2568 const InputReaderConfiguration* config, uint32_t changes) {
2569 InputMapper::configure(when, config, changes);
2570
2571 if (!changes) { // first time only
2572 mCursorScrollAccumulator.configure(getDevice());
2573
2574 // Configure basic parameters.
2575 configureParameters();
2576
2577 // Configure device mode.
2578 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002579 case Parameters::MODE_POINTER_RELATIVE:
2580 // Should not happen during first time configuration.
2581 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2582 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002583 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002584 case Parameters::MODE_POINTER:
2585 mSource = AINPUT_SOURCE_MOUSE;
2586 mXPrecision = 1.0f;
2587 mYPrecision = 1.0f;
2588 mXScale = 1.0f;
2589 mYScale = 1.0f;
2590 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2591 break;
2592 case Parameters::MODE_NAVIGATION:
2593 mSource = AINPUT_SOURCE_TRACKBALL;
2594 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2595 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2596 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2597 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2598 break;
2599 }
2600
2601 mVWheelScale = 1.0f;
2602 mHWheelScale = 1.0f;
2603 }
2604
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002605 if ((!changes && config->pointerCapture)
2606 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2607 if (config->pointerCapture) {
2608 if (mParameters.mode == Parameters::MODE_POINTER) {
2609 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2610 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2611 // Keep PointerController around in order to preserve the pointer position.
2612 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2613 } else {
2614 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2615 }
2616 } else {
2617 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2618 mParameters.mode = Parameters::MODE_POINTER;
2619 mSource = AINPUT_SOURCE_MOUSE;
2620 } else {
2621 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2622 }
2623 }
2624 bumpGeneration();
2625 if (changes) {
2626 getDevice()->notifyReset(when);
2627 }
2628 }
2629
Michael Wrightd02c5b62014-02-10 15:10:22 -08002630 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2631 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2632 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2633 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2634 }
2635
2636 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002637 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002638 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002639 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002640 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002641 if (internalViewport) {
2642 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002644 }
Andrii Kulian620f6d92018-09-14 16:51:59 -07002645 getPolicy()->updatePointerDisplay();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002646 bumpGeneration();
2647 }
2648}
2649
2650void CursorInputMapper::configureParameters() {
2651 mParameters.mode = Parameters::MODE_POINTER;
2652 String8 cursorModeString;
2653 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2654 if (cursorModeString == "navigation") {
2655 mParameters.mode = Parameters::MODE_NAVIGATION;
2656 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2657 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2658 }
2659 }
2660
2661 mParameters.orientationAware = false;
2662 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2663 mParameters.orientationAware);
2664
2665 mParameters.hasAssociatedDisplay = false;
2666 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2667 mParameters.hasAssociatedDisplay = true;
2668 }
2669}
2670
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002671void CursorInputMapper::dumpParameters(std::string& dump) {
2672 dump += INDENT3 "Parameters:\n";
2673 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 toString(mParameters.hasAssociatedDisplay));
2675
2676 switch (mParameters.mode) {
2677 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002678 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002679 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002680 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002681 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002682 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002684 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002685 break;
2686 default:
2687 ALOG_ASSERT(false);
2688 }
2689
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002690 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002691 toString(mParameters.orientationAware));
2692}
2693
2694void CursorInputMapper::reset(nsecs_t when) {
2695 mButtonState = 0;
2696 mDownTime = 0;
2697
2698 mPointerVelocityControl.reset();
2699 mWheelXVelocityControl.reset();
2700 mWheelYVelocityControl.reset();
2701
2702 mCursorButtonAccumulator.reset(getDevice());
2703 mCursorMotionAccumulator.reset(getDevice());
2704 mCursorScrollAccumulator.reset(getDevice());
2705
2706 InputMapper::reset(when);
2707}
2708
2709void CursorInputMapper::process(const RawEvent* rawEvent) {
2710 mCursorButtonAccumulator.process(rawEvent);
2711 mCursorMotionAccumulator.process(rawEvent);
2712 mCursorScrollAccumulator.process(rawEvent);
2713
2714 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2715 sync(rawEvent->when);
2716 }
2717}
2718
2719void CursorInputMapper::sync(nsecs_t when) {
2720 int32_t lastButtonState = mButtonState;
2721 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2722 mButtonState = currentButtonState;
2723
2724 bool wasDown = isPointerDown(lastButtonState);
2725 bool down = isPointerDown(currentButtonState);
2726 bool downChanged;
2727 if (!wasDown && down) {
2728 mDownTime = when;
2729 downChanged = true;
2730 } else if (wasDown && !down) {
2731 downChanged = true;
2732 } else {
2733 downChanged = false;
2734 }
2735 nsecs_t downTime = mDownTime;
2736 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002737 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2738 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002739
2740 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2741 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2742 bool moved = deltaX != 0 || deltaY != 0;
2743
2744 // Rotate delta according to orientation if needed.
2745 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2746 && (deltaX != 0.0f || deltaY != 0.0f)) {
2747 rotateDelta(mOrientation, &deltaX, &deltaY);
2748 }
2749
2750 // Move the pointer.
2751 PointerProperties pointerProperties;
2752 pointerProperties.clear();
2753 pointerProperties.id = 0;
2754 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2755
2756 PointerCoords pointerCoords;
2757 pointerCoords.clear();
2758
2759 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2760 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2761 bool scrolled = vscroll != 0 || hscroll != 0;
2762
Yi Kong9b14ac62018-07-17 13:48:38 -07002763 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2764 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765
2766 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2767
2768 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002769 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002770 if (moved || scrolled || buttonsChanged) {
2771 mPointerController->setPresentation(
2772 PointerControllerInterface::PRESENTATION_POINTER);
2773
2774 if (moved) {
2775 mPointerController->move(deltaX, deltaY);
2776 }
2777
2778 if (buttonsChanged) {
2779 mPointerController->setButtonState(currentButtonState);
2780 }
2781
2782 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2783 }
2784
2785 float x, y;
2786 mPointerController->getPosition(&x, &y);
2787 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2788 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002789 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2790 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Andrii Kulian620f6d92018-09-14 16:51:59 -07002791 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 } else {
2793 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2794 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2795 displayId = ADISPLAY_ID_NONE;
2796 }
2797
2798 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2799
2800 // Moving an external trackball or mouse should wake the device.
2801 // We don't do this for internal cursor devices to prevent them from waking up
2802 // the device in your pocket.
2803 // TODO: Use the input device configuration to control this behavior more finely.
2804 uint32_t policyFlags = 0;
2805 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002806 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807 }
2808
2809 // Synthesize key down from buttons if needed.
2810 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002811 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812
2813 // Send motion event.
2814 if (downChanged || moved || scrolled || buttonsChanged) {
2815 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002816 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002817 int32_t motionEventAction;
2818 if (downChanged) {
2819 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002820 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002821 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2822 } else {
2823 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2824 }
2825
Michael Wright7b159c92015-05-14 14:48:03 +01002826 if (buttonsReleased) {
2827 BitSet32 released(buttonsReleased);
2828 while (!released.isEmpty()) {
2829 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2830 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002831 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2832 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002833 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2834 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002835 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002836 mXPrecision, mYPrecision, downTime);
2837 getListener()->notifyMotion(&releaseArgs);
2838 }
2839 }
2840
Prabir Pradhan42611e02018-11-27 14:04:02 -08002841 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2842 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Michael Wright7b159c92015-05-14 14:48:03 +01002843 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002844 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 mXPrecision, mYPrecision, downTime);
2846 getListener()->notifyMotion(&args);
2847
Michael Wright7b159c92015-05-14 14:48:03 +01002848 if (buttonsPressed) {
2849 BitSet32 pressed(buttonsPressed);
2850 while (!pressed.isEmpty()) {
2851 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2852 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002853 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2854 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2855 actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002856 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002857 mXPrecision, mYPrecision, downTime);
2858 getListener()->notifyMotion(&pressArgs);
2859 }
2860 }
2861
2862 ALOG_ASSERT(buttonState == currentButtonState);
2863
Michael Wrightd02c5b62014-02-10 15:10:22 -08002864 // Send hover move after UP to tell the application that the mouse is hovering now.
2865 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002866 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002867 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2868 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002870 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002871 mXPrecision, mYPrecision, downTime);
2872 getListener()->notifyMotion(&hoverArgs);
2873 }
2874
2875 // Send scroll events.
2876 if (scrolled) {
2877 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2878 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2879
Prabir Pradhan42611e02018-11-27 14:04:02 -08002880 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2881 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002882 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002883 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002884 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002885 mXPrecision, mYPrecision, downTime);
2886 getListener()->notifyMotion(&scrollArgs);
2887 }
2888 }
2889
2890 // Synthesize key up from buttons if needed.
2891 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002892 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002893
2894 mCursorMotionAccumulator.finishSync();
2895 mCursorScrollAccumulator.finishSync();
2896}
2897
2898int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2899 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2900 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2901 } else {
2902 return AKEY_STATE_UNKNOWN;
2903 }
2904}
2905
2906void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002907 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2909 }
2910}
2911
Prashant Malani1941ff52015-08-11 18:29:28 -07002912// --- RotaryEncoderInputMapper ---
2913
2914RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002915 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002916 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2917}
2918
2919RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2920}
2921
2922uint32_t RotaryEncoderInputMapper::getSources() {
2923 return mSource;
2924}
2925
2926void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2927 InputMapper::populateDeviceInfo(info);
2928
2929 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002930 float res = 0.0f;
2931 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2932 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2933 }
2934 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2935 mScalingFactor)) {
2936 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2937 "default to 1.0!\n");
2938 mScalingFactor = 1.0f;
2939 }
2940 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2941 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002942 }
2943}
2944
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002945void RotaryEncoderInputMapper::dump(std::string& dump) {
2946 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2947 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002948 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2949}
2950
2951void RotaryEncoderInputMapper::configure(nsecs_t when,
2952 const InputReaderConfiguration* config, uint32_t changes) {
2953 InputMapper::configure(when, config, changes);
2954 if (!changes) {
2955 mRotaryEncoderScrollAccumulator.configure(getDevice());
2956 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002957 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002958 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002959 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002960 if (internalViewport) {
2961 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002962 } else {
2963 mOrientation = DISPLAY_ORIENTATION_0;
2964 }
2965 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002966}
2967
2968void RotaryEncoderInputMapper::reset(nsecs_t when) {
2969 mRotaryEncoderScrollAccumulator.reset(getDevice());
2970
2971 InputMapper::reset(when);
2972}
2973
2974void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2975 mRotaryEncoderScrollAccumulator.process(rawEvent);
2976
2977 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2978 sync(rawEvent->when);
2979 }
2980}
2981
2982void RotaryEncoderInputMapper::sync(nsecs_t when) {
2983 PointerCoords pointerCoords;
2984 pointerCoords.clear();
2985
2986 PointerProperties pointerProperties;
2987 pointerProperties.clear();
2988 pointerProperties.id = 0;
2989 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2990
2991 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2992 bool scrolled = scroll != 0;
2993
2994 // This is not a pointer, so it's not associated with a display.
2995 int32_t displayId = ADISPLAY_ID_NONE;
2996
2997 // Moving the rotary encoder should wake the device (if specified).
2998 uint32_t policyFlags = 0;
2999 if (scrolled && getDevice()->isExternal()) {
3000 policyFlags |= POLICY_FLAG_WAKE;
3001 }
3002
Ivan Podogovad437252016-09-29 16:29:55 +01003003 if (mOrientation == DISPLAY_ORIENTATION_180) {
3004 scroll = -scroll;
3005 }
3006
Prashant Malani1941ff52015-08-11 18:29:28 -07003007 // Send motion event.
3008 if (scrolled) {
3009 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003010 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003011
Prabir Pradhan42611e02018-11-27 14:04:02 -08003012 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3013 mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003014 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3015 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003016 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003017 0, 0, 0);
3018 getListener()->notifyMotion(&scrollArgs);
3019 }
3020
3021 mRotaryEncoderScrollAccumulator.finishSync();
3022}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023
3024// --- TouchInputMapper ---
3025
3026TouchInputMapper::TouchInputMapper(InputDevice* device) :
3027 InputMapper(device),
3028 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3029 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003030 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003031 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3032}
3033
3034TouchInputMapper::~TouchInputMapper() {
3035}
3036
3037uint32_t TouchInputMapper::getSources() {
3038 return mSource;
3039}
3040
3041void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3042 InputMapper::populateDeviceInfo(info);
3043
3044 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3045 info->addMotionRange(mOrientedRanges.x);
3046 info->addMotionRange(mOrientedRanges.y);
3047 info->addMotionRange(mOrientedRanges.pressure);
3048
3049 if (mOrientedRanges.haveSize) {
3050 info->addMotionRange(mOrientedRanges.size);
3051 }
3052
3053 if (mOrientedRanges.haveTouchSize) {
3054 info->addMotionRange(mOrientedRanges.touchMajor);
3055 info->addMotionRange(mOrientedRanges.touchMinor);
3056 }
3057
3058 if (mOrientedRanges.haveToolSize) {
3059 info->addMotionRange(mOrientedRanges.toolMajor);
3060 info->addMotionRange(mOrientedRanges.toolMinor);
3061 }
3062
3063 if (mOrientedRanges.haveOrientation) {
3064 info->addMotionRange(mOrientedRanges.orientation);
3065 }
3066
3067 if (mOrientedRanges.haveDistance) {
3068 info->addMotionRange(mOrientedRanges.distance);
3069 }
3070
3071 if (mOrientedRanges.haveTilt) {
3072 info->addMotionRange(mOrientedRanges.tilt);
3073 }
3074
3075 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3076 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3077 0.0f);
3078 }
3079 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3080 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3081 0.0f);
3082 }
3083 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3084 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3085 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3086 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3087 x.fuzz, x.resolution);
3088 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3089 y.fuzz, y.resolution);
3090 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3091 x.fuzz, x.resolution);
3092 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3093 y.fuzz, y.resolution);
3094 }
3095 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3096 }
3097}
3098
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003099void TouchInputMapper::dump(std::string& dump) {
3100 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003101 dumpParameters(dump);
3102 dumpVirtualKeys(dump);
3103 dumpRawPointerAxes(dump);
3104 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003105 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003106 dumpSurface(dump);
3107
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003108 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3109 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3110 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3111 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3112 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3113 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3114 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3115 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3116 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3117 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3118 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3119 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3120 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3121 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3122 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3123 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3124 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003125
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003126 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3127 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003128 mLastRawState.rawPointerData.pointerCount);
3129 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3130 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003131 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3133 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3134 "toolType=%d, isHovering=%s\n", i,
3135 pointer.id, pointer.x, pointer.y, pointer.pressure,
3136 pointer.touchMajor, pointer.touchMinor,
3137 pointer.toolMajor, pointer.toolMinor,
3138 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3139 pointer.toolType, toString(pointer.isHovering));
3140 }
3141
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003142 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3143 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003144 mLastCookedState.cookedPointerData.pointerCount);
3145 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3146 const PointerProperties& pointerProperties =
3147 mLastCookedState.cookedPointerData.pointerProperties[i];
3148 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003149 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003150 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3151 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3152 "toolType=%d, isHovering=%s\n", i,
3153 pointerProperties.id,
3154 pointerCoords.getX(),
3155 pointerCoords.getY(),
3156 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3157 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3158 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3159 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3160 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3161 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3162 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3163 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3164 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003165 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003166 }
3167
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003168 dump += INDENT3 "Stylus Fusion:\n";
3169 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003170 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003171 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3172 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003173 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003175 dumpStylusState(dump, mExternalStylusState);
3176
Michael Wrightd02c5b62014-02-10 15:10:22 -08003177 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003178 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3179 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003183 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003185 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003187 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 mPointerGestureMaxSwipeWidth);
3189 }
3190}
3191
Santos Cordonfa5cf462017-04-05 10:37:00 -07003192const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3193 switch (deviceMode) {
3194 case DEVICE_MODE_DISABLED:
3195 return "disabled";
3196 case DEVICE_MODE_DIRECT:
3197 return "direct";
3198 case DEVICE_MODE_UNSCALED:
3199 return "unscaled";
3200 case DEVICE_MODE_NAVIGATION:
3201 return "navigation";
3202 case DEVICE_MODE_POINTER:
3203 return "pointer";
3204 }
3205 return "unknown";
3206}
3207
Michael Wrightd02c5b62014-02-10 15:10:22 -08003208void TouchInputMapper::configure(nsecs_t when,
3209 const InputReaderConfiguration* config, uint32_t changes) {
3210 InputMapper::configure(when, config, changes);
3211
3212 mConfig = *config;
3213
3214 if (!changes) { // first time only
3215 // Configure basic parameters.
3216 configureParameters();
3217
3218 // Configure common accumulators.
3219 mCursorScrollAccumulator.configure(getDevice());
3220 mTouchButtonAccumulator.configure(getDevice());
3221
3222 // Configure absolute axis information.
3223 configureRawPointerAxes();
3224
3225 // Prepare input device calibration.
3226 parseCalibration();
3227 resolveCalibration();
3228 }
3229
Michael Wright842500e2015-03-13 17:32:02 -07003230 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003231 // Update location calibration to reflect current settings
3232 updateAffineTransformation();
3233 }
3234
Michael Wrightd02c5b62014-02-10 15:10:22 -08003235 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3236 // Update pointer speed.
3237 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3238 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3239 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3240 }
3241
3242 bool resetNeeded = false;
3243 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3244 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003245 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3246 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247 // Configure device sources, surface dimensions, orientation and
3248 // scaling factors.
3249 configureSurface(when, &resetNeeded);
3250 }
3251
3252 if (changes && resetNeeded) {
3253 // Send reset, unless this is the first time the device has been configured,
3254 // in which case the reader will call reset itself after all mappers are ready.
3255 getDevice()->notifyReset(when);
3256 }
3257}
3258
Michael Wright842500e2015-03-13 17:32:02 -07003259void TouchInputMapper::resolveExternalStylusPresence() {
3260 Vector<InputDeviceInfo> devices;
3261 mContext->getExternalStylusDevices(devices);
3262 mExternalStylusConnected = !devices.isEmpty();
3263
3264 if (!mExternalStylusConnected) {
3265 resetExternalStylus();
3266 }
3267}
3268
Michael Wrightd02c5b62014-02-10 15:10:22 -08003269void TouchInputMapper::configureParameters() {
3270 // Use the pointer presentation mode for devices that do not support distinct
3271 // multitouch. The spot-based presentation relies on being able to accurately
3272 // locate two or more fingers on the touch pad.
3273 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003274 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275
3276 String8 gestureModeString;
3277 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3278 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003279 if (gestureModeString == "single-touch") {
3280 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3281 } else if (gestureModeString == "multi-touch") {
3282 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 } else if (gestureModeString != "default") {
3284 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3285 }
3286 }
3287
3288 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3289 // The device is a touch screen.
3290 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3291 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3292 // The device is a pointing device like a track pad.
3293 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3294 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3295 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3296 // The device is a cursor device with a touch pad attached.
3297 // By default don't use the touch pad to move the pointer.
3298 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3299 } else {
3300 // The device is a touch pad of unknown purpose.
3301 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3302 }
3303
3304 mParameters.hasButtonUnderPad=
3305 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3306
3307 String8 deviceTypeString;
3308 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3309 deviceTypeString)) {
3310 if (deviceTypeString == "touchScreen") {
3311 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3312 } else if (deviceTypeString == "touchPad") {
3313 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3314 } else if (deviceTypeString == "touchNavigation") {
3315 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3316 } else if (deviceTypeString == "pointer") {
3317 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3318 } else if (deviceTypeString != "default") {
3319 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3320 }
3321 }
3322
3323 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3324 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3325 mParameters.orientationAware);
3326
3327 mParameters.hasAssociatedDisplay = false;
3328 mParameters.associatedDisplayIsExternal = false;
3329 if (mParameters.orientationAware
3330 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3331 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3332 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003333 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3334 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003335 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003336 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003337 uniqueDisplayId);
3338 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003339 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003340 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003341 if (getDevice()->getAssociatedDisplayPort()) {
3342 mParameters.hasAssociatedDisplay = true;
3343 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003344
3345 // Initial downs on external touch devices should wake the device.
3346 // Normally we don't do this for internal touch screens to prevent them from waking
3347 // up in your pocket but you can enable it using the input device configuration.
3348 mParameters.wake = getDevice()->isExternal();
3349 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3350 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351}
3352
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003353void TouchInputMapper::dumpParameters(std::string& dump) {
3354 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355
3356 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003357 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003358 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003360 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003361 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 break;
3363 default:
3364 assert(false);
3365 }
3366
3367 switch (mParameters.deviceType) {
3368 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003369 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003370 break;
3371 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003372 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003373 break;
3374 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003375 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 break;
3377 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003378 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 break;
3380 default:
3381 ALOG_ASSERT(false);
3382 }
3383
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003384 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003385 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003386 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003387 toString(mParameters.associatedDisplayIsExternal),
3388 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003389 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003390 toString(mParameters.orientationAware));
3391}
3392
3393void TouchInputMapper::configureRawPointerAxes() {
3394 mRawPointerAxes.clear();
3395}
3396
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003397void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3398 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003399 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3400 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3401 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3402 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3403 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3404 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3405 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3406 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3407 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3408 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3410 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3411 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3412}
3413
Michael Wright842500e2015-03-13 17:32:02 -07003414bool TouchInputMapper::hasExternalStylus() const {
3415 return mExternalStylusConnected;
3416}
3417
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003418/**
3419 * Determine which DisplayViewport to use.
3420 * 1. If display port is specified, return the matching viewport. If matching viewport not
3421 * found, then return.
3422 * 2. If a device has associated display, get the matching viewport by either unique id or by
3423 * the display type (internal or external).
3424 * 3. Otherwise, use a non-display viewport.
3425 */
3426std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3427 if (mParameters.hasAssociatedDisplay) {
3428 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3429 if (displayPort) {
3430 // Find the viewport that contains the same port
3431 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3432 if (!v) {
3433 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3434 "but the corresponding viewport is not found.",
3435 getDeviceName().c_str(), *displayPort);
3436 }
3437 return v;
3438 }
3439
3440 if (!mParameters.uniqueDisplayId.empty()) {
3441 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3442 }
3443
3444 ViewportType viewportTypeToUse;
3445 if (mParameters.associatedDisplayIsExternal) {
3446 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3447 } else {
3448 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3449 }
3450 return mConfig.getDisplayViewportByType(viewportTypeToUse);
3451 }
3452
3453 DisplayViewport newViewport;
3454 // Raw width and height in the natural orientation.
3455 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3456 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3457 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3458 return std::make_optional(newViewport);
3459}
3460
Michael Wrightd02c5b62014-02-10 15:10:22 -08003461void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3462 int32_t oldDeviceMode = mDeviceMode;
3463
Michael Wright842500e2015-03-13 17:32:02 -07003464 resolveExternalStylusPresence();
3465
Michael Wrightd02c5b62014-02-10 15:10:22 -08003466 // Determine device mode.
3467 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3468 && mConfig.pointerGesturesEnabled) {
3469 mSource = AINPUT_SOURCE_MOUSE;
3470 mDeviceMode = DEVICE_MODE_POINTER;
3471 if (hasStylus()) {
3472 mSource |= AINPUT_SOURCE_STYLUS;
3473 }
3474 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3475 && mParameters.hasAssociatedDisplay) {
3476 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3477 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003478 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003479 mSource |= AINPUT_SOURCE_STYLUS;
3480 }
Michael Wright2f78b682015-06-12 15:25:08 +01003481 if (hasExternalStylus()) {
3482 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3483 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003484 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3485 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3486 mDeviceMode = DEVICE_MODE_NAVIGATION;
3487 } else {
3488 mSource = AINPUT_SOURCE_TOUCHPAD;
3489 mDeviceMode = DEVICE_MODE_UNSCALED;
3490 }
3491
3492 // Ensure we have valid X and Y axes.
3493 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003494 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003495 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003496 mDeviceMode = DEVICE_MODE_DISABLED;
3497 return;
3498 }
3499
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003500 // Get associated display dimensions.
3501 std::optional<DisplayViewport> newViewport = findViewport();
3502 if (!newViewport) {
3503 ALOGI("Touch device '%s' could not query the properties of its associated "
3504 "display. The device will be inoperable until the display size "
3505 "becomes available.",
3506 getDeviceName().c_str());
3507 mDeviceMode = DEVICE_MODE_DISABLED;
3508 return;
3509 }
3510
Michael Wrightd02c5b62014-02-10 15:10:22 -08003511 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003512 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3513 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003514
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003515 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003517 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003518
3519 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3520 // Convert rotated viewport to natural surface coordinates.
3521 int32_t naturalLogicalWidth, naturalLogicalHeight;
3522 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3523 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3524 int32_t naturalDeviceWidth, naturalDeviceHeight;
3525 switch (mViewport.orientation) {
3526 case DISPLAY_ORIENTATION_90:
3527 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3528 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3529 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3530 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3531 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3532 naturalPhysicalTop = mViewport.physicalLeft;
3533 naturalDeviceWidth = mViewport.deviceHeight;
3534 naturalDeviceHeight = mViewport.deviceWidth;
3535 break;
3536 case DISPLAY_ORIENTATION_180:
3537 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3538 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3539 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3540 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3541 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3542 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3543 naturalDeviceWidth = mViewport.deviceWidth;
3544 naturalDeviceHeight = mViewport.deviceHeight;
3545 break;
3546 case DISPLAY_ORIENTATION_270:
3547 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3548 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3549 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3550 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3551 naturalPhysicalLeft = mViewport.physicalTop;
3552 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3553 naturalDeviceWidth = mViewport.deviceHeight;
3554 naturalDeviceHeight = mViewport.deviceWidth;
3555 break;
3556 case DISPLAY_ORIENTATION_0:
3557 default:
3558 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3559 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3560 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3561 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3562 naturalPhysicalLeft = mViewport.physicalLeft;
3563 naturalPhysicalTop = mViewport.physicalTop;
3564 naturalDeviceWidth = mViewport.deviceWidth;
3565 naturalDeviceHeight = mViewport.deviceHeight;
3566 break;
3567 }
3568
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003569 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3570 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3571 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3572 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3573 }
3574
Michael Wright358bcc72018-08-21 04:01:07 +01003575 mPhysicalWidth = naturalPhysicalWidth;
3576 mPhysicalHeight = naturalPhysicalHeight;
3577 mPhysicalLeft = naturalPhysicalLeft;
3578 mPhysicalTop = naturalPhysicalTop;
3579
Michael Wrightd02c5b62014-02-10 15:10:22 -08003580 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3581 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3582 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3583 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3584
3585 mSurfaceOrientation = mParameters.orientationAware ?
3586 mViewport.orientation : DISPLAY_ORIENTATION_0;
3587 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003588 mPhysicalWidth = rawWidth;
3589 mPhysicalHeight = rawHeight;
3590 mPhysicalLeft = 0;
3591 mPhysicalTop = 0;
3592
Michael Wrightd02c5b62014-02-10 15:10:22 -08003593 mSurfaceWidth = rawWidth;
3594 mSurfaceHeight = rawHeight;
3595 mSurfaceLeft = 0;
3596 mSurfaceTop = 0;
3597 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3598 }
3599 }
3600
3601 // If moving between pointer modes, need to reset some state.
3602 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3603 if (deviceModeChanged) {
3604 mOrientedRanges.clear();
3605 }
3606
3607 // Create pointer controller if needed.
3608 if (mDeviceMode == DEVICE_MODE_POINTER ||
3609 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003610 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003611 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
Andrii Kulian620f6d92018-09-14 16:51:59 -07003612 getPolicy()->updatePointerDisplay();
3613 } else if (viewportChanged) {
3614 getPolicy()->updatePointerDisplay();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003615 }
3616 } else {
3617 mPointerController.clear();
3618 }
3619
3620 if (viewportChanged || deviceModeChanged) {
3621 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3622 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003623 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3625
3626 // Configure X and Y factors.
3627 mXScale = float(mSurfaceWidth) / rawWidth;
3628 mYScale = float(mSurfaceHeight) / rawHeight;
3629 mXTranslate = -mSurfaceLeft;
3630 mYTranslate = -mSurfaceTop;
3631 mXPrecision = 1.0f / mXScale;
3632 mYPrecision = 1.0f / mYScale;
3633
3634 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3635 mOrientedRanges.x.source = mSource;
3636 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3637 mOrientedRanges.y.source = mSource;
3638
3639 configureVirtualKeys();
3640
3641 // Scale factor for terms that are not oriented in a particular axis.
3642 // If the pixels are square then xScale == yScale otherwise we fake it
3643 // by choosing an average.
3644 mGeometricScale = avg(mXScale, mYScale);
3645
3646 // Size of diagonal axis.
3647 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3648
3649 // Size factors.
3650 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3651 if (mRawPointerAxes.touchMajor.valid
3652 && mRawPointerAxes.touchMajor.maxValue != 0) {
3653 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3654 } else if (mRawPointerAxes.toolMajor.valid
3655 && mRawPointerAxes.toolMajor.maxValue != 0) {
3656 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3657 } else {
3658 mSizeScale = 0.0f;
3659 }
3660
3661 mOrientedRanges.haveTouchSize = true;
3662 mOrientedRanges.haveToolSize = true;
3663 mOrientedRanges.haveSize = true;
3664
3665 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3666 mOrientedRanges.touchMajor.source = mSource;
3667 mOrientedRanges.touchMajor.min = 0;
3668 mOrientedRanges.touchMajor.max = diagonalSize;
3669 mOrientedRanges.touchMajor.flat = 0;
3670 mOrientedRanges.touchMajor.fuzz = 0;
3671 mOrientedRanges.touchMajor.resolution = 0;
3672
3673 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3674 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3675
3676 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3677 mOrientedRanges.toolMajor.source = mSource;
3678 mOrientedRanges.toolMajor.min = 0;
3679 mOrientedRanges.toolMajor.max = diagonalSize;
3680 mOrientedRanges.toolMajor.flat = 0;
3681 mOrientedRanges.toolMajor.fuzz = 0;
3682 mOrientedRanges.toolMajor.resolution = 0;
3683
3684 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3685 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3686
3687 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3688 mOrientedRanges.size.source = mSource;
3689 mOrientedRanges.size.min = 0;
3690 mOrientedRanges.size.max = 1.0;
3691 mOrientedRanges.size.flat = 0;
3692 mOrientedRanges.size.fuzz = 0;
3693 mOrientedRanges.size.resolution = 0;
3694 } else {
3695 mSizeScale = 0.0f;
3696 }
3697
3698 // Pressure factors.
3699 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003700 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003701 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3702 || mCalibration.pressureCalibration
3703 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3704 if (mCalibration.havePressureScale) {
3705 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003706 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 } else if (mRawPointerAxes.pressure.valid
3708 && mRawPointerAxes.pressure.maxValue != 0) {
3709 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3710 }
3711 }
3712
3713 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3714 mOrientedRanges.pressure.source = mSource;
3715 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003716 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003717 mOrientedRanges.pressure.flat = 0;
3718 mOrientedRanges.pressure.fuzz = 0;
3719 mOrientedRanges.pressure.resolution = 0;
3720
3721 // Tilt
3722 mTiltXCenter = 0;
3723 mTiltXScale = 0;
3724 mTiltYCenter = 0;
3725 mTiltYScale = 0;
3726 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3727 if (mHaveTilt) {
3728 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3729 mRawPointerAxes.tiltX.maxValue);
3730 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3731 mRawPointerAxes.tiltY.maxValue);
3732 mTiltXScale = M_PI / 180;
3733 mTiltYScale = M_PI / 180;
3734
3735 mOrientedRanges.haveTilt = true;
3736
3737 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3738 mOrientedRanges.tilt.source = mSource;
3739 mOrientedRanges.tilt.min = 0;
3740 mOrientedRanges.tilt.max = M_PI_2;
3741 mOrientedRanges.tilt.flat = 0;
3742 mOrientedRanges.tilt.fuzz = 0;
3743 mOrientedRanges.tilt.resolution = 0;
3744 }
3745
3746 // Orientation
3747 mOrientationScale = 0;
3748 if (mHaveTilt) {
3749 mOrientedRanges.haveOrientation = true;
3750
3751 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3752 mOrientedRanges.orientation.source = mSource;
3753 mOrientedRanges.orientation.min = -M_PI;
3754 mOrientedRanges.orientation.max = M_PI;
3755 mOrientedRanges.orientation.flat = 0;
3756 mOrientedRanges.orientation.fuzz = 0;
3757 mOrientedRanges.orientation.resolution = 0;
3758 } else if (mCalibration.orientationCalibration !=
3759 Calibration::ORIENTATION_CALIBRATION_NONE) {
3760 if (mCalibration.orientationCalibration
3761 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3762 if (mRawPointerAxes.orientation.valid) {
3763 if (mRawPointerAxes.orientation.maxValue > 0) {
3764 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3765 } else if (mRawPointerAxes.orientation.minValue < 0) {
3766 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3767 } else {
3768 mOrientationScale = 0;
3769 }
3770 }
3771 }
3772
3773 mOrientedRanges.haveOrientation = true;
3774
3775 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3776 mOrientedRanges.orientation.source = mSource;
3777 mOrientedRanges.orientation.min = -M_PI_2;
3778 mOrientedRanges.orientation.max = M_PI_2;
3779 mOrientedRanges.orientation.flat = 0;
3780 mOrientedRanges.orientation.fuzz = 0;
3781 mOrientedRanges.orientation.resolution = 0;
3782 }
3783
3784 // Distance
3785 mDistanceScale = 0;
3786 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3787 if (mCalibration.distanceCalibration
3788 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3789 if (mCalibration.haveDistanceScale) {
3790 mDistanceScale = mCalibration.distanceScale;
3791 } else {
3792 mDistanceScale = 1.0f;
3793 }
3794 }
3795
3796 mOrientedRanges.haveDistance = true;
3797
3798 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3799 mOrientedRanges.distance.source = mSource;
3800 mOrientedRanges.distance.min =
3801 mRawPointerAxes.distance.minValue * mDistanceScale;
3802 mOrientedRanges.distance.max =
3803 mRawPointerAxes.distance.maxValue * mDistanceScale;
3804 mOrientedRanges.distance.flat = 0;
3805 mOrientedRanges.distance.fuzz =
3806 mRawPointerAxes.distance.fuzz * mDistanceScale;
3807 mOrientedRanges.distance.resolution = 0;
3808 }
3809
3810 // Compute oriented precision, scales and ranges.
3811 // Note that the maximum value reported is an inclusive maximum value so it is one
3812 // unit less than the total width or height of surface.
3813 switch (mSurfaceOrientation) {
3814 case DISPLAY_ORIENTATION_90:
3815 case DISPLAY_ORIENTATION_270:
3816 mOrientedXPrecision = mYPrecision;
3817 mOrientedYPrecision = mXPrecision;
3818
3819 mOrientedRanges.x.min = mYTranslate;
3820 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3821 mOrientedRanges.x.flat = 0;
3822 mOrientedRanges.x.fuzz = 0;
3823 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3824
3825 mOrientedRanges.y.min = mXTranslate;
3826 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3827 mOrientedRanges.y.flat = 0;
3828 mOrientedRanges.y.fuzz = 0;
3829 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3830 break;
3831
3832 default:
3833 mOrientedXPrecision = mXPrecision;
3834 mOrientedYPrecision = mYPrecision;
3835
3836 mOrientedRanges.x.min = mXTranslate;
3837 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3838 mOrientedRanges.x.flat = 0;
3839 mOrientedRanges.x.fuzz = 0;
3840 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3841
3842 mOrientedRanges.y.min = mYTranslate;
3843 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3844 mOrientedRanges.y.flat = 0;
3845 mOrientedRanges.y.fuzz = 0;
3846 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3847 break;
3848 }
3849
Jason Gerecke71b16e82014-03-10 09:47:59 -07003850 // Location
3851 updateAffineTransformation();
3852
Michael Wrightd02c5b62014-02-10 15:10:22 -08003853 if (mDeviceMode == DEVICE_MODE_POINTER) {
3854 // Compute pointer gesture detection parameters.
3855 float rawDiagonal = hypotf(rawWidth, rawHeight);
3856 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3857
3858 // Scale movements such that one whole swipe of the touch pad covers a
3859 // given area relative to the diagonal size of the display when no acceleration
3860 // is applied.
3861 // Assume that the touch pad has a square aspect ratio such that movements in
3862 // X and Y of the same number of raw units cover the same physical distance.
3863 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3864 * displayDiagonal / rawDiagonal;
3865 mPointerYMovementScale = mPointerXMovementScale;
3866
3867 // Scale zooms to cover a smaller range of the display than movements do.
3868 // This value determines the area around the pointer that is affected by freeform
3869 // pointer gestures.
3870 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3871 * displayDiagonal / rawDiagonal;
3872 mPointerYZoomScale = mPointerXZoomScale;
3873
3874 // Max width between pointers to detect a swipe gesture is more than some fraction
3875 // of the diagonal axis of the touch pad. Touches that are wider than this are
3876 // translated into freeform gestures.
3877 mPointerGestureMaxSwipeWidth =
3878 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3879
3880 // Abort current pointer usages because the state has changed.
3881 abortPointerUsage(when, 0 /*policyFlags*/);
3882 }
3883
3884 // Inform the dispatcher about the changes.
3885 *outResetNeeded = true;
3886 bumpGeneration();
3887 }
3888}
3889
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003890void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003891 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003892 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3893 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3894 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3895 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003896 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3897 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3898 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3899 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003900 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901}
3902
3903void TouchInputMapper::configureVirtualKeys() {
3904 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3905 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3906
3907 mVirtualKeys.clear();
3908
3909 if (virtualKeyDefinitions.size() == 0) {
3910 return;
3911 }
3912
3913 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3914
3915 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3916 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003917 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3918 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919
3920 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3921 const VirtualKeyDefinition& virtualKeyDefinition =
3922 virtualKeyDefinitions[i];
3923
3924 mVirtualKeys.add();
3925 VirtualKey& virtualKey = mVirtualKeys.editTop();
3926
3927 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3928 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003929 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003930 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003931 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3932 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003933 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3934 virtualKey.scanCode);
3935 mVirtualKeys.pop(); // drop the key
3936 continue;
3937 }
3938
3939 virtualKey.keyCode = keyCode;
3940 virtualKey.flags = flags;
3941
3942 // convert the key definition's display coordinates into touch coordinates for a hit box
3943 int32_t halfWidth = virtualKeyDefinition.width / 2;
3944 int32_t halfHeight = virtualKeyDefinition.height / 2;
3945
3946 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3947 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3948 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3949 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3950 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3951 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3952 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3953 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3954 }
3955}
3956
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003957void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003958 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003959 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003960
3961 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3962 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003963 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003964 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3965 i, virtualKey.scanCode, virtualKey.keyCode,
3966 virtualKey.hitLeft, virtualKey.hitRight,
3967 virtualKey.hitTop, virtualKey.hitBottom);
3968 }
3969 }
3970}
3971
3972void TouchInputMapper::parseCalibration() {
3973 const PropertyMap& in = getDevice()->getConfiguration();
3974 Calibration& out = mCalibration;
3975
3976 // Size
3977 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3978 String8 sizeCalibrationString;
3979 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3980 if (sizeCalibrationString == "none") {
3981 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3982 } else if (sizeCalibrationString == "geometric") {
3983 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3984 } else if (sizeCalibrationString == "diameter") {
3985 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3986 } else if (sizeCalibrationString == "box") {
3987 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3988 } else if (sizeCalibrationString == "area") {
3989 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3990 } else if (sizeCalibrationString != "default") {
3991 ALOGW("Invalid value for touch.size.calibration: '%s'",
3992 sizeCalibrationString.string());
3993 }
3994 }
3995
3996 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3997 out.sizeScale);
3998 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3999 out.sizeBias);
4000 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4001 out.sizeIsSummed);
4002
4003 // Pressure
4004 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4005 String8 pressureCalibrationString;
4006 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4007 if (pressureCalibrationString == "none") {
4008 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4009 } else if (pressureCalibrationString == "physical") {
4010 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4011 } else if (pressureCalibrationString == "amplitude") {
4012 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4013 } else if (pressureCalibrationString != "default") {
4014 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4015 pressureCalibrationString.string());
4016 }
4017 }
4018
4019 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4020 out.pressureScale);
4021
4022 // Orientation
4023 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4024 String8 orientationCalibrationString;
4025 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4026 if (orientationCalibrationString == "none") {
4027 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4028 } else if (orientationCalibrationString == "interpolated") {
4029 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4030 } else if (orientationCalibrationString == "vector") {
4031 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4032 } else if (orientationCalibrationString != "default") {
4033 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4034 orientationCalibrationString.string());
4035 }
4036 }
4037
4038 // Distance
4039 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4040 String8 distanceCalibrationString;
4041 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4042 if (distanceCalibrationString == "none") {
4043 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4044 } else if (distanceCalibrationString == "scaled") {
4045 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4046 } else if (distanceCalibrationString != "default") {
4047 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4048 distanceCalibrationString.string());
4049 }
4050 }
4051
4052 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4053 out.distanceScale);
4054
4055 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4056 String8 coverageCalibrationString;
4057 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4058 if (coverageCalibrationString == "none") {
4059 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4060 } else if (coverageCalibrationString == "box") {
4061 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4062 } else if (coverageCalibrationString != "default") {
4063 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4064 coverageCalibrationString.string());
4065 }
4066 }
4067}
4068
4069void TouchInputMapper::resolveCalibration() {
4070 // Size
4071 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4072 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4073 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4074 }
4075 } else {
4076 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4077 }
4078
4079 // Pressure
4080 if (mRawPointerAxes.pressure.valid) {
4081 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4082 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4083 }
4084 } else {
4085 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4086 }
4087
4088 // Orientation
4089 if (mRawPointerAxes.orientation.valid) {
4090 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4091 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4092 }
4093 } else {
4094 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4095 }
4096
4097 // Distance
4098 if (mRawPointerAxes.distance.valid) {
4099 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4100 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4101 }
4102 } else {
4103 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4104 }
4105
4106 // Coverage
4107 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4108 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4109 }
4110}
4111
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004112void TouchInputMapper::dumpCalibration(std::string& dump) {
4113 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114
4115 // Size
4116 switch (mCalibration.sizeCalibration) {
4117 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004118 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119 break;
4120 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004121 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004122 break;
4123 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004124 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004125 break;
4126 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004127 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004128 break;
4129 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004130 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004131 break;
4132 default:
4133 ALOG_ASSERT(false);
4134 }
4135
4136 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004137 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 mCalibration.sizeScale);
4139 }
4140
4141 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004142 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 mCalibration.sizeBias);
4144 }
4145
4146 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 toString(mCalibration.sizeIsSummed));
4149 }
4150
4151 // Pressure
4152 switch (mCalibration.pressureCalibration) {
4153 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004154 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004155 break;
4156 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004157 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004158 break;
4159 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 break;
4162 default:
4163 ALOG_ASSERT(false);
4164 }
4165
4166 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 mCalibration.pressureScale);
4169 }
4170
4171 // Orientation
4172 switch (mCalibration.orientationCalibration) {
4173 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004174 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004175 break;
4176 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004178 break;
4179 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 break;
4182 default:
4183 ALOG_ASSERT(false);
4184 }
4185
4186 // Distance
4187 switch (mCalibration.distanceCalibration) {
4188 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004189 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004190 break;
4191 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004192 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004193 break;
4194 default:
4195 ALOG_ASSERT(false);
4196 }
4197
4198 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004199 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004200 mCalibration.distanceScale);
4201 }
4202
4203 switch (mCalibration.coverageCalibration) {
4204 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 break;
4207 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004208 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004209 break;
4210 default:
4211 ALOG_ASSERT(false);
4212 }
4213}
4214
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004215void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4216 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004217
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4219 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4220 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4221 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4222 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4223 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004224}
4225
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004226void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004227 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4228 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004229}
4230
Michael Wrightd02c5b62014-02-10 15:10:22 -08004231void TouchInputMapper::reset(nsecs_t when) {
4232 mCursorButtonAccumulator.reset(getDevice());
4233 mCursorScrollAccumulator.reset(getDevice());
4234 mTouchButtonAccumulator.reset(getDevice());
4235
4236 mPointerVelocityControl.reset();
4237 mWheelXVelocityControl.reset();
4238 mWheelYVelocityControl.reset();
4239
Michael Wright842500e2015-03-13 17:32:02 -07004240 mRawStatesPending.clear();
4241 mCurrentRawState.clear();
4242 mCurrentCookedState.clear();
4243 mLastRawState.clear();
4244 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245 mPointerUsage = POINTER_USAGE_NONE;
4246 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004247 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004248 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004249 mDownTime = 0;
4250
4251 mCurrentVirtualKey.down = false;
4252
4253 mPointerGesture.reset();
4254 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004255 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
Yi Kong9b14ac62018-07-17 13:48:38 -07004257 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4259 mPointerController->clearSpots();
4260 }
4261
4262 InputMapper::reset(when);
4263}
4264
Michael Wright842500e2015-03-13 17:32:02 -07004265void TouchInputMapper::resetExternalStylus() {
4266 mExternalStylusState.clear();
4267 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004268 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004269 mExternalStylusDataPending = false;
4270}
4271
Michael Wright43fd19f2015-04-21 19:02:58 +01004272void TouchInputMapper::clearStylusDataPendingFlags() {
4273 mExternalStylusDataPending = false;
4274 mExternalStylusFusionTimeout = LLONG_MAX;
4275}
4276
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277void TouchInputMapper::process(const RawEvent* rawEvent) {
4278 mCursorButtonAccumulator.process(rawEvent);
4279 mCursorScrollAccumulator.process(rawEvent);
4280 mTouchButtonAccumulator.process(rawEvent);
4281
4282 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4283 sync(rawEvent->when);
4284 }
4285}
4286
4287void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004288 const RawState* last = mRawStatesPending.isEmpty() ?
4289 &mCurrentRawState : &mRawStatesPending.top();
4290
4291 // Push a new state.
4292 mRawStatesPending.push();
4293 RawState* next = &mRawStatesPending.editTop();
4294 next->clear();
4295 next->when = when;
4296
Michael Wrightd02c5b62014-02-10 15:10:22 -08004297 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004298 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004299 | mCursorButtonAccumulator.getButtonState();
4300
Michael Wright842500e2015-03-13 17:32:02 -07004301 // Sync scroll
4302 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4303 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 mCursorScrollAccumulator.finishSync();
4305
Michael Wright842500e2015-03-13 17:32:02 -07004306 // Sync touch
4307 syncTouch(when, next);
4308
4309 // Assign pointer ids.
4310 if (!mHavePointerIds) {
4311 assignPointerIds(last, next);
4312 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004313
4314#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004315 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4316 "hovering ids 0x%08x -> 0x%08x",
4317 last->rawPointerData.pointerCount,
4318 next->rawPointerData.pointerCount,
4319 last->rawPointerData.touchingIdBits.value,
4320 next->rawPointerData.touchingIdBits.value,
4321 last->rawPointerData.hoveringIdBits.value,
4322 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323#endif
4324
Michael Wright842500e2015-03-13 17:32:02 -07004325 processRawTouches(false /*timeout*/);
4326}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004327
Michael Wright842500e2015-03-13 17:32:02 -07004328void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4330 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004331 mCurrentRawState.clear();
4332 mRawStatesPending.clear();
4333 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 }
4335
Michael Wright842500e2015-03-13 17:32:02 -07004336 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4337 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4338 // touching the current state will only observe the events that have been dispatched to the
4339 // rest of the pipeline.
4340 const size_t N = mRawStatesPending.size();
4341 size_t count;
4342 for(count = 0; count < N; count++) {
4343 const RawState& next = mRawStatesPending[count];
4344
4345 // A failure to assign the stylus id means that we're waiting on stylus data
4346 // and so should defer the rest of the pipeline.
4347 if (assignExternalStylusId(next, timeout)) {
4348 break;
4349 }
4350
4351 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004352 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004353 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004354 if (mCurrentRawState.when < mLastRawState.when) {
4355 mCurrentRawState.when = mLastRawState.when;
4356 }
Michael Wright842500e2015-03-13 17:32:02 -07004357 cookAndDispatch(mCurrentRawState.when);
4358 }
4359 if (count != 0) {
4360 mRawStatesPending.removeItemsAt(0, count);
4361 }
4362
Michael Wright842500e2015-03-13 17:32:02 -07004363 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004364 if (timeout) {
4365 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4366 clearStylusDataPendingFlags();
4367 mCurrentRawState.copyFrom(mLastRawState);
4368#if DEBUG_STYLUS_FUSION
4369 ALOGD("Timeout expired, synthesizing event with new stylus data");
4370#endif
4371 cookAndDispatch(when);
4372 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4373 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4374 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4375 }
Michael Wright842500e2015-03-13 17:32:02 -07004376 }
4377}
4378
4379void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4380 // Always start with a clean state.
4381 mCurrentCookedState.clear();
4382
4383 // Apply stylus buttons to current raw state.
4384 applyExternalStylusButtonState(when);
4385
4386 // Handle policy on initial down or hover events.
4387 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4388 && mCurrentRawState.rawPointerData.pointerCount != 0;
4389
4390 uint32_t policyFlags = 0;
4391 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4392 if (initialDown || buttonsPressed) {
4393 // If this is a touch screen, hide the pointer on an initial down.
4394 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4395 getContext()->fadePointer();
4396 }
4397
4398 if (mParameters.wake) {
4399 policyFlags |= POLICY_FLAG_WAKE;
4400 }
4401 }
4402
4403 // Consume raw off-screen touches before cooking pointer data.
4404 // If touches are consumed, subsequent code will not receive any pointer data.
4405 if (consumeRawTouches(when, policyFlags)) {
4406 mCurrentRawState.rawPointerData.clear();
4407 }
4408
4409 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4410 // with cooked pointer data that has the same ids and indices as the raw data.
4411 // The following code can use either the raw or cooked data, as needed.
4412 cookPointerData();
4413
4414 // Apply stylus pressure to current cooked state.
4415 applyExternalStylusTouchState(when);
4416
4417 // Synthesize key down from raw buttons if needed.
4418 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004419 mViewport.displayId, policyFlags,
4420 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004421
4422 // Dispatch the touches either directly or by translation through a pointer on screen.
4423 if (mDeviceMode == DEVICE_MODE_POINTER) {
4424 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4425 !idBits.isEmpty(); ) {
4426 uint32_t id = idBits.clearFirstMarkedBit();
4427 const RawPointerData::Pointer& pointer =
4428 mCurrentRawState.rawPointerData.pointerForId(id);
4429 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4430 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4431 mCurrentCookedState.stylusIdBits.markBit(id);
4432 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4433 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4434 mCurrentCookedState.fingerIdBits.markBit(id);
4435 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4436 mCurrentCookedState.mouseIdBits.markBit(id);
4437 }
4438 }
4439 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4440 !idBits.isEmpty(); ) {
4441 uint32_t id = idBits.clearFirstMarkedBit();
4442 const RawPointerData::Pointer& pointer =
4443 mCurrentRawState.rawPointerData.pointerForId(id);
4444 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4445 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4446 mCurrentCookedState.stylusIdBits.markBit(id);
4447 }
4448 }
4449
4450 // Stylus takes precedence over all tools, then mouse, then finger.
4451 PointerUsage pointerUsage = mPointerUsage;
4452 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4453 mCurrentCookedState.mouseIdBits.clear();
4454 mCurrentCookedState.fingerIdBits.clear();
4455 pointerUsage = POINTER_USAGE_STYLUS;
4456 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4457 mCurrentCookedState.fingerIdBits.clear();
4458 pointerUsage = POINTER_USAGE_MOUSE;
4459 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4460 isPointerDown(mCurrentRawState.buttonState)) {
4461 pointerUsage = POINTER_USAGE_GESTURES;
4462 }
4463
4464 dispatchPointerUsage(when, policyFlags, pointerUsage);
4465 } else {
4466 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004467 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004468 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4469 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4470
4471 mPointerController->setButtonState(mCurrentRawState.buttonState);
4472 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4473 mCurrentCookedState.cookedPointerData.idToIndex,
4474 mCurrentCookedState.cookedPointerData.touchingIdBits);
4475 }
4476
Michael Wright8e812822015-06-22 16:18:21 +01004477 if (!mCurrentMotionAborted) {
4478 dispatchButtonRelease(when, policyFlags);
4479 dispatchHoverExit(when, policyFlags);
4480 dispatchTouches(when, policyFlags);
4481 dispatchHoverEnterAndMove(when, policyFlags);
4482 dispatchButtonPress(when, policyFlags);
4483 }
4484
4485 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4486 mCurrentMotionAborted = false;
4487 }
Michael Wright842500e2015-03-13 17:32:02 -07004488 }
4489
4490 // Synthesize key up from raw buttons if needed.
4491 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004492 mViewport.displayId, policyFlags,
4493 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004494
4495 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004496 mCurrentRawState.rawVScroll = 0;
4497 mCurrentRawState.rawHScroll = 0;
4498
4499 // Copy current touch to last touch in preparation for the next cycle.
4500 mLastRawState.copyFrom(mCurrentRawState);
4501 mLastCookedState.copyFrom(mCurrentCookedState);
4502}
4503
4504void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004505 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004506 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4507 }
4508}
4509
4510void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004511 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4512 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004513
Michael Wright53dca3a2015-04-23 17:39:53 +01004514 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4515 float pressure = mExternalStylusState.pressure;
4516 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4517 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4518 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4519 }
4520 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4521 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4522
4523 PointerProperties& properties =
4524 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004525 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4526 properties.toolType = mExternalStylusState.toolType;
4527 }
4528 }
4529}
4530
4531bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4532 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4533 return false;
4534 }
4535
4536 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4537 && state.rawPointerData.pointerCount != 0;
4538 if (initialDown) {
4539 if (mExternalStylusState.pressure != 0.0f) {
4540#if DEBUG_STYLUS_FUSION
4541 ALOGD("Have both stylus and touch data, beginning fusion");
4542#endif
4543 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4544 } else if (timeout) {
4545#if DEBUG_STYLUS_FUSION
4546 ALOGD("Timeout expired, assuming touch is not a stylus.");
4547#endif
4548 resetExternalStylus();
4549 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004550 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4551 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004552 }
4553#if DEBUG_STYLUS_FUSION
4554 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004555 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004556#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004557 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004558 return true;
4559 }
4560 }
4561
4562 // Check if the stylus pointer has gone up.
4563 if (mExternalStylusId != -1 &&
4564 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4565#if DEBUG_STYLUS_FUSION
4566 ALOGD("Stylus pointer is going up");
4567#endif
4568 mExternalStylusId = -1;
4569 }
4570
4571 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004572}
4573
4574void TouchInputMapper::timeoutExpired(nsecs_t when) {
4575 if (mDeviceMode == DEVICE_MODE_POINTER) {
4576 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4577 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4578 }
Michael Wright842500e2015-03-13 17:32:02 -07004579 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004580 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004581 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004582 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4583 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004584 }
4585 }
4586}
4587
4588void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004589 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004590 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004591 // We're either in the middle of a fused stream of data or we're waiting on data before
4592 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4593 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004594 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004595 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004596 }
4597}
4598
4599bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4600 // Check for release of a virtual key.
4601 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004602 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004603 // Pointer went up while virtual key was down.
4604 mCurrentVirtualKey.down = false;
4605 if (!mCurrentVirtualKey.ignored) {
4606#if DEBUG_VIRTUAL_KEYS
4607 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4608 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4609#endif
4610 dispatchVirtualKey(when, policyFlags,
4611 AKEY_EVENT_ACTION_UP,
4612 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4613 }
4614 return true;
4615 }
4616
Michael Wright842500e2015-03-13 17:32:02 -07004617 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4618 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4619 const RawPointerData::Pointer& pointer =
4620 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4622 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4623 // Pointer is still within the space of the virtual key.
4624 return true;
4625 }
4626 }
4627
4628 // Pointer left virtual key area or another pointer also went down.
4629 // Send key cancellation but do not consume the touch yet.
4630 // This is useful when the user swipes through from the virtual key area
4631 // into the main display surface.
4632 mCurrentVirtualKey.down = false;
4633 if (!mCurrentVirtualKey.ignored) {
4634#if DEBUG_VIRTUAL_KEYS
4635 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4636 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4637#endif
4638 dispatchVirtualKey(when, policyFlags,
4639 AKEY_EVENT_ACTION_UP,
4640 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4641 | AKEY_EVENT_FLAG_CANCELED);
4642 }
4643 }
4644
Michael Wright842500e2015-03-13 17:32:02 -07004645 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4646 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004647 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004648 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4649 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004650 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4651 // If exactly one pointer went down, check for virtual key hit.
4652 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004653 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004654 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4655 if (virtualKey) {
4656 mCurrentVirtualKey.down = true;
4657 mCurrentVirtualKey.downTime = when;
4658 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4659 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4660 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4661 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4662
4663 if (!mCurrentVirtualKey.ignored) {
4664#if DEBUG_VIRTUAL_KEYS
4665 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4666 mCurrentVirtualKey.keyCode,
4667 mCurrentVirtualKey.scanCode);
4668#endif
4669 dispatchVirtualKey(when, policyFlags,
4670 AKEY_EVENT_ACTION_DOWN,
4671 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4672 }
4673 }
4674 }
4675 return true;
4676 }
4677 }
4678
4679 // Disable all virtual key touches that happen within a short time interval of the
4680 // most recent touch within the screen area. The idea is to filter out stray
4681 // virtual key presses when interacting with the touch screen.
4682 //
4683 // Problems we're trying to solve:
4684 //
4685 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4686 // virtual key area that is implemented by a separate touch panel and accidentally
4687 // triggers a virtual key.
4688 //
4689 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4690 // area and accidentally triggers a virtual key. This often happens when virtual keys
4691 // are layed out below the screen near to where the on screen keyboard's space bar
4692 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004693 if (mConfig.virtualKeyQuietTime > 0 &&
4694 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4696 }
4697 return false;
4698}
4699
4700void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4701 int32_t keyEventAction, int32_t keyEventFlags) {
4702 int32_t keyCode = mCurrentVirtualKey.keyCode;
4703 int32_t scanCode = mCurrentVirtualKey.scanCode;
4704 nsecs_t downTime = mCurrentVirtualKey.downTime;
4705 int32_t metaState = mContext->getGlobalMetaState();
4706 policyFlags |= POLICY_FLAG_VIRTUAL;
4707
Prabir Pradhan42611e02018-11-27 14:04:02 -08004708 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4709 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004710 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004711 getListener()->notifyKey(&args);
4712}
4713
Michael Wright8e812822015-06-22 16:18:21 +01004714void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4715 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4716 if (!currentIdBits.isEmpty()) {
4717 int32_t metaState = getContext()->getGlobalMetaState();
4718 int32_t buttonState = mCurrentCookedState.buttonState;
4719 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4720 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004721 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004722 mCurrentCookedState.cookedPointerData.pointerProperties,
4723 mCurrentCookedState.cookedPointerData.pointerCoords,
4724 mCurrentCookedState.cookedPointerData.idToIndex,
4725 currentIdBits, -1,
4726 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4727 mCurrentMotionAborted = true;
4728 }
4729}
4730
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004732 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4733 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004735 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736
4737 if (currentIdBits == lastIdBits) {
4738 if (!currentIdBits.isEmpty()) {
4739 // No pointer id changes so this is a move event.
4740 // The listener takes care of batching moves so we don't have to deal with that here.
4741 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004742 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004743 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004744 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004745 mCurrentCookedState.cookedPointerData.pointerProperties,
4746 mCurrentCookedState.cookedPointerData.pointerCoords,
4747 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 currentIdBits, -1,
4749 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4750 }
4751 } else {
4752 // There may be pointers going up and pointers going down and pointers moving
4753 // all at the same time.
4754 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4755 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4756 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4757 BitSet32 dispatchedIdBits(lastIdBits.value);
4758
4759 // Update last coordinates of pointers that have moved so that we observe the new
4760 // pointer positions at the same time as other pointers that have just gone up.
4761 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004762 mCurrentCookedState.cookedPointerData.pointerProperties,
4763 mCurrentCookedState.cookedPointerData.pointerCoords,
4764 mCurrentCookedState.cookedPointerData.idToIndex,
4765 mLastCookedState.cookedPointerData.pointerProperties,
4766 mLastCookedState.cookedPointerData.pointerCoords,
4767 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004769 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004770 moveNeeded = true;
4771 }
4772
4773 // Dispatch pointer up events.
4774 while (!upIdBits.isEmpty()) {
4775 uint32_t upId = upIdBits.clearFirstMarkedBit();
4776
4777 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004778 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004779 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004780 mLastCookedState.cookedPointerData.pointerProperties,
4781 mLastCookedState.cookedPointerData.pointerCoords,
4782 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004783 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 dispatchedIdBits.clearBit(upId);
4785 }
4786
4787 // Dispatch move events if any of the remaining pointers moved from their old locations.
4788 // Although applications receive new locations as part of individual pointer up
4789 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004790 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004791 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4792 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004793 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004794 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004795 mCurrentCookedState.cookedPointerData.pointerProperties,
4796 mCurrentCookedState.cookedPointerData.pointerCoords,
4797 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004798 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004799 }
4800
4801 // Dispatch pointer down events using the new pointer locations.
4802 while (!downIdBits.isEmpty()) {
4803 uint32_t downId = downIdBits.clearFirstMarkedBit();
4804 dispatchedIdBits.markBit(downId);
4805
4806 if (dispatchedIdBits.count() == 1) {
4807 // First pointer is going down. Set down time.
4808 mDownTime = when;
4809 }
4810
4811 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004812 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004813 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004814 mCurrentCookedState.cookedPointerData.pointerProperties,
4815 mCurrentCookedState.cookedPointerData.pointerCoords,
4816 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004817 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004818 }
4819 }
4820}
4821
4822void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4823 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004824 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4825 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004826 int32_t metaState = getContext()->getGlobalMetaState();
4827 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004828 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004829 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004830 mLastCookedState.cookedPointerData.pointerProperties,
4831 mLastCookedState.cookedPointerData.pointerCoords,
4832 mLastCookedState.cookedPointerData.idToIndex,
4833 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004834 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4835 mSentHoverEnter = false;
4836 }
4837}
4838
4839void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004840 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4841 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004842 int32_t metaState = getContext()->getGlobalMetaState();
4843 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004844 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004845 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004846 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004847 mCurrentCookedState.cookedPointerData.pointerProperties,
4848 mCurrentCookedState.cookedPointerData.pointerCoords,
4849 mCurrentCookedState.cookedPointerData.idToIndex,
4850 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4852 mSentHoverEnter = true;
4853 }
4854
4855 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004856 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004857 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004858 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004859 mCurrentCookedState.cookedPointerData.pointerProperties,
4860 mCurrentCookedState.cookedPointerData.pointerCoords,
4861 mCurrentCookedState.cookedPointerData.idToIndex,
4862 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4864 }
4865}
4866
Michael Wright7b159c92015-05-14 14:48:03 +01004867void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4868 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4869 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4870 const int32_t metaState = getContext()->getGlobalMetaState();
4871 int32_t buttonState = mLastCookedState.buttonState;
4872 while (!releasedButtons.isEmpty()) {
4873 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4874 buttonState &= ~actionButton;
4875 dispatchMotion(when, policyFlags, mSource,
4876 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4877 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004878 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004879 mCurrentCookedState.cookedPointerData.pointerProperties,
4880 mCurrentCookedState.cookedPointerData.pointerCoords,
4881 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4882 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4883 }
4884}
4885
4886void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4887 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4888 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4889 const int32_t metaState = getContext()->getGlobalMetaState();
4890 int32_t buttonState = mLastCookedState.buttonState;
4891 while (!pressedButtons.isEmpty()) {
4892 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4893 buttonState |= actionButton;
4894 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4895 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004896 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004897 mCurrentCookedState.cookedPointerData.pointerProperties,
4898 mCurrentCookedState.cookedPointerData.pointerCoords,
4899 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4900 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4901 }
4902}
4903
4904const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4905 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4906 return cookedPointerData.touchingIdBits;
4907 }
4908 return cookedPointerData.hoveringIdBits;
4909}
4910
Michael Wrightd02c5b62014-02-10 15:10:22 -08004911void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004912 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004913
Michael Wright842500e2015-03-13 17:32:02 -07004914 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004915 mCurrentCookedState.deviceTimestamp =
4916 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004917 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4918 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4919 mCurrentRawState.rawPointerData.hoveringIdBits;
4920 mCurrentCookedState.cookedPointerData.touchingIdBits =
4921 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004922
Michael Wright7b159c92015-05-14 14:48:03 +01004923 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4924 mCurrentCookedState.buttonState = 0;
4925 } else {
4926 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4927 }
4928
Michael Wrightd02c5b62014-02-10 15:10:22 -08004929 // Walk through the the active pointers and map device coordinates onto
4930 // surface coordinates and adjust for display orientation.
4931 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004932 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933
4934 // Size
4935 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4936 switch (mCalibration.sizeCalibration) {
4937 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4938 case Calibration::SIZE_CALIBRATION_DIAMETER:
4939 case Calibration::SIZE_CALIBRATION_BOX:
4940 case Calibration::SIZE_CALIBRATION_AREA:
4941 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4942 touchMajor = in.touchMajor;
4943 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4944 toolMajor = in.toolMajor;
4945 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4946 size = mRawPointerAxes.touchMinor.valid
4947 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4948 } else if (mRawPointerAxes.touchMajor.valid) {
4949 toolMajor = touchMajor = in.touchMajor;
4950 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4951 ? in.touchMinor : in.touchMajor;
4952 size = mRawPointerAxes.touchMinor.valid
4953 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4954 } else if (mRawPointerAxes.toolMajor.valid) {
4955 touchMajor = toolMajor = in.toolMajor;
4956 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4957 ? in.toolMinor : in.toolMajor;
4958 size = mRawPointerAxes.toolMinor.valid
4959 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4960 } else {
4961 ALOG_ASSERT(false, "No touch or tool axes. "
4962 "Size calibration should have been resolved to NONE.");
4963 touchMajor = 0;
4964 touchMinor = 0;
4965 toolMajor = 0;
4966 toolMinor = 0;
4967 size = 0;
4968 }
4969
4970 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004971 uint32_t touchingCount =
4972 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004973 if (touchingCount > 1) {
4974 touchMajor /= touchingCount;
4975 touchMinor /= touchingCount;
4976 toolMajor /= touchingCount;
4977 toolMinor /= touchingCount;
4978 size /= touchingCount;
4979 }
4980 }
4981
4982 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4983 touchMajor *= mGeometricScale;
4984 touchMinor *= mGeometricScale;
4985 toolMajor *= mGeometricScale;
4986 toolMinor *= mGeometricScale;
4987 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4988 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4989 touchMinor = touchMajor;
4990 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4991 toolMinor = toolMajor;
4992 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4993 touchMinor = touchMajor;
4994 toolMinor = toolMajor;
4995 }
4996
4997 mCalibration.applySizeScaleAndBias(&touchMajor);
4998 mCalibration.applySizeScaleAndBias(&touchMinor);
4999 mCalibration.applySizeScaleAndBias(&toolMajor);
5000 mCalibration.applySizeScaleAndBias(&toolMinor);
5001 size *= mSizeScale;
5002 break;
5003 default:
5004 touchMajor = 0;
5005 touchMinor = 0;
5006 toolMajor = 0;
5007 toolMinor = 0;
5008 size = 0;
5009 break;
5010 }
5011
5012 // Pressure
5013 float pressure;
5014 switch (mCalibration.pressureCalibration) {
5015 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5016 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5017 pressure = in.pressure * mPressureScale;
5018 break;
5019 default:
5020 pressure = in.isHovering ? 0 : 1;
5021 break;
5022 }
5023
5024 // Tilt and Orientation
5025 float tilt;
5026 float orientation;
5027 if (mHaveTilt) {
5028 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5029 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5030 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5031 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5032 } else {
5033 tilt = 0;
5034
5035 switch (mCalibration.orientationCalibration) {
5036 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5037 orientation = in.orientation * mOrientationScale;
5038 break;
5039 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5040 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5041 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5042 if (c1 != 0 || c2 != 0) {
5043 orientation = atan2f(c1, c2) * 0.5f;
5044 float confidence = hypotf(c1, c2);
5045 float scale = 1.0f + confidence / 16.0f;
5046 touchMajor *= scale;
5047 touchMinor /= scale;
5048 toolMajor *= scale;
5049 toolMinor /= scale;
5050 } else {
5051 orientation = 0;
5052 }
5053 break;
5054 }
5055 default:
5056 orientation = 0;
5057 }
5058 }
5059
5060 // Distance
5061 float distance;
5062 switch (mCalibration.distanceCalibration) {
5063 case Calibration::DISTANCE_CALIBRATION_SCALED:
5064 distance = in.distance * mDistanceScale;
5065 break;
5066 default:
5067 distance = 0;
5068 }
5069
5070 // Coverage
5071 int32_t rawLeft, rawTop, rawRight, rawBottom;
5072 switch (mCalibration.coverageCalibration) {
5073 case Calibration::COVERAGE_CALIBRATION_BOX:
5074 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5075 rawRight = in.toolMinor & 0x0000ffff;
5076 rawBottom = in.toolMajor & 0x0000ffff;
5077 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5078 break;
5079 default:
5080 rawLeft = rawTop = rawRight = rawBottom = 0;
5081 break;
5082 }
5083
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005084 // Adjust X,Y coords for device calibration
5085 // TODO: Adjust coverage coords?
5086 float xTransformed = in.x, yTransformed = in.y;
5087 mAffineTransform.applyTo(xTransformed, yTransformed);
5088
5089 // Adjust X, Y, and coverage coords for surface orientation.
5090 float x, y;
5091 float left, top, right, bottom;
5092
Michael Wrightd02c5b62014-02-10 15:10:22 -08005093 switch (mSurfaceOrientation) {
5094 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005095 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5096 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5098 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5099 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5100 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5101 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005102 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5104 }
5105 break;
5106 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005107 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005108 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005109 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5110 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5112 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5113 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005114 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5116 }
5117 break;
5118 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005119 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005120 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005121 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5122 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005123 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5124 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5125 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005126 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005127 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5128 }
5129 break;
5130 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005131 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5132 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005133 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5134 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5135 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5136 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5137 break;
5138 }
5139
5140 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005141 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005142 out.clear();
5143 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5145 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5146 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5148 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5150 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5151 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5152 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5153 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5155 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5156 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5157 } else {
5158 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5159 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5160 }
5161
5162 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005163 PointerProperties& properties =
5164 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005165 uint32_t id = in.id;
5166 properties.clear();
5167 properties.id = id;
5168 properties.toolType = in.toolType;
5169
5170 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005171 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005172 }
5173}
5174
5175void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5176 PointerUsage pointerUsage) {
5177 if (pointerUsage != mPointerUsage) {
5178 abortPointerUsage(when, policyFlags);
5179 mPointerUsage = pointerUsage;
5180 }
5181
5182 switch (mPointerUsage) {
5183 case POINTER_USAGE_GESTURES:
5184 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5185 break;
5186 case POINTER_USAGE_STYLUS:
5187 dispatchPointerStylus(when, policyFlags);
5188 break;
5189 case POINTER_USAGE_MOUSE:
5190 dispatchPointerMouse(when, policyFlags);
5191 break;
5192 default:
5193 break;
5194 }
5195}
5196
5197void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5198 switch (mPointerUsage) {
5199 case POINTER_USAGE_GESTURES:
5200 abortPointerGestures(when, policyFlags);
5201 break;
5202 case POINTER_USAGE_STYLUS:
5203 abortPointerStylus(when, policyFlags);
5204 break;
5205 case POINTER_USAGE_MOUSE:
5206 abortPointerMouse(when, policyFlags);
5207 break;
5208 default:
5209 break;
5210 }
5211
5212 mPointerUsage = POINTER_USAGE_NONE;
5213}
5214
5215void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5216 bool isTimeout) {
5217 // Update current gesture coordinates.
5218 bool cancelPreviousGesture, finishPreviousGesture;
5219 bool sendEvents = preparePointerGestures(when,
5220 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5221 if (!sendEvents) {
5222 return;
5223 }
5224 if (finishPreviousGesture) {
5225 cancelPreviousGesture = false;
5226 }
5227
5228 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005229 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5230 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005231 if (finishPreviousGesture || cancelPreviousGesture) {
5232 mPointerController->clearSpots();
5233 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005234
5235 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5236 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5237 mPointerGesture.currentGestureIdToIndex,
5238 mPointerGesture.currentGestureIdBits);
5239 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005240 } else {
5241 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5242 }
5243
5244 // Show or hide the pointer if needed.
5245 switch (mPointerGesture.currentGestureMode) {
5246 case PointerGesture::NEUTRAL:
5247 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005248 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5249 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005250 // Remind the user of where the pointer is after finishing a gesture with spots.
5251 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5252 }
5253 break;
5254 case PointerGesture::TAP:
5255 case PointerGesture::TAP_DRAG:
5256 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5257 case PointerGesture::HOVER:
5258 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005259 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005260 // Unfade the pointer when the current gesture manipulates the
5261 // area directly under the pointer.
5262 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5263 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005264 case PointerGesture::FREEFORM:
5265 // Fade the pointer when the current gesture manipulates a different
5266 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005267 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005268 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5269 } else {
5270 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5271 }
5272 break;
5273 }
5274
5275 // Send events!
5276 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005277 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005278
5279 // Update last coordinates of pointers that have moved so that we observe the new
5280 // pointer positions at the same time as other pointers that have just gone up.
5281 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5282 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5283 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5284 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5285 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5286 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5287 bool moveNeeded = false;
5288 if (down && !cancelPreviousGesture && !finishPreviousGesture
5289 && !mPointerGesture.lastGestureIdBits.isEmpty()
5290 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5291 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5292 & mPointerGesture.lastGestureIdBits.value);
5293 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5294 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5295 mPointerGesture.lastGestureProperties,
5296 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5297 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005298 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005299 moveNeeded = true;
5300 }
5301 }
5302
5303 // Send motion events for all pointers that went up or were canceled.
5304 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5305 if (!dispatchedGestureIdBits.isEmpty()) {
5306 if (cancelPreviousGesture) {
5307 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005308 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005309 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005310 mPointerGesture.lastGestureProperties,
5311 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005312 dispatchedGestureIdBits, -1, 0,
5313 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005314
5315 dispatchedGestureIdBits.clear();
5316 } else {
5317 BitSet32 upGestureIdBits;
5318 if (finishPreviousGesture) {
5319 upGestureIdBits = dispatchedGestureIdBits;
5320 } else {
5321 upGestureIdBits.value = dispatchedGestureIdBits.value
5322 & ~mPointerGesture.currentGestureIdBits.value;
5323 }
5324 while (!upGestureIdBits.isEmpty()) {
5325 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5326
5327 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005328 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005329 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005330 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 mPointerGesture.lastGestureProperties,
5332 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5333 dispatchedGestureIdBits, id,
5334 0, 0, mPointerGesture.downTime);
5335
5336 dispatchedGestureIdBits.clearBit(id);
5337 }
5338 }
5339 }
5340
5341 // Send motion events for all pointers that moved.
5342 if (moveNeeded) {
5343 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005344 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005345 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346 mPointerGesture.currentGestureProperties,
5347 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5348 dispatchedGestureIdBits, -1,
5349 0, 0, mPointerGesture.downTime);
5350 }
5351
5352 // Send motion events for all pointers that went down.
5353 if (down) {
5354 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5355 & ~dispatchedGestureIdBits.value);
5356 while (!downGestureIdBits.isEmpty()) {
5357 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5358 dispatchedGestureIdBits.markBit(id);
5359
5360 if (dispatchedGestureIdBits.count() == 1) {
5361 mPointerGesture.downTime = when;
5362 }
5363
5364 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005365 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005366 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 mPointerGesture.currentGestureProperties,
5368 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5369 dispatchedGestureIdBits, id,
5370 0, 0, mPointerGesture.downTime);
5371 }
5372 }
5373
5374 // Send motion events for hover.
5375 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5376 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005377 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005378 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005379 mPointerGesture.currentGestureProperties,
5380 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5381 mPointerGesture.currentGestureIdBits, -1,
5382 0, 0, mPointerGesture.downTime);
5383 } else if (dispatchedGestureIdBits.isEmpty()
5384 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5385 // Synthesize a hover move event after all pointers go up to indicate that
5386 // the pointer is hovering again even if the user is not currently touching
5387 // the touch pad. This ensures that a view will receive a fresh hover enter
5388 // event after a tap.
5389 float x, y;
5390 mPointerController->getPosition(&x, &y);
5391
5392 PointerProperties pointerProperties;
5393 pointerProperties.clear();
5394 pointerProperties.id = 0;
5395 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5396
5397 PointerCoords pointerCoords;
5398 pointerCoords.clear();
5399 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5400 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5401
Andrii Kulian620f6d92018-09-14 16:51:59 -07005402 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhan42611e02018-11-27 14:04:02 -08005403 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, displayId, mSource,
5404 mViewport.displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005405 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005406 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005407 0, 0, mPointerGesture.downTime);
5408 getListener()->notifyMotion(&args);
5409 }
5410
5411 // Update state.
5412 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5413 if (!down) {
5414 mPointerGesture.lastGestureIdBits.clear();
5415 } else {
5416 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5417 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5418 uint32_t id = idBits.clearFirstMarkedBit();
5419 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5420 mPointerGesture.lastGestureProperties[index].copyFrom(
5421 mPointerGesture.currentGestureProperties[index]);
5422 mPointerGesture.lastGestureCoords[index].copyFrom(
5423 mPointerGesture.currentGestureCoords[index]);
5424 mPointerGesture.lastGestureIdToIndex[id] = index;
5425 }
5426 }
5427}
5428
5429void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5430 // Cancel previously dispatches pointers.
5431 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5432 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005433 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005434 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005435 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005436 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005437 mPointerGesture.lastGestureProperties,
5438 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5439 mPointerGesture.lastGestureIdBits, -1,
5440 0, 0, mPointerGesture.downTime);
5441 }
5442
5443 // Reset the current pointer gesture.
5444 mPointerGesture.reset();
5445 mPointerVelocityControl.reset();
5446
5447 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005448 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005449 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5450 mPointerController->clearSpots();
5451 }
5452}
5453
5454bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5455 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5456 *outCancelPreviousGesture = false;
5457 *outFinishPreviousGesture = false;
5458
5459 // Handle TAP timeout.
5460 if (isTimeout) {
5461#if DEBUG_GESTURES
5462 ALOGD("Gestures: Processing timeout");
5463#endif
5464
5465 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5466 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5467 // The tap/drag timeout has not yet expired.
5468 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5469 + mConfig.pointerGestureTapDragInterval);
5470 } else {
5471 // The tap is finished.
5472#if DEBUG_GESTURES
5473 ALOGD("Gestures: TAP finished");
5474#endif
5475 *outFinishPreviousGesture = true;
5476
5477 mPointerGesture.activeGestureId = -1;
5478 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5479 mPointerGesture.currentGestureIdBits.clear();
5480
5481 mPointerVelocityControl.reset();
5482 return true;
5483 }
5484 }
5485
5486 // We did not handle this timeout.
5487 return false;
5488 }
5489
Michael Wright842500e2015-03-13 17:32:02 -07005490 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5491 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005492
5493 // Update the velocity tracker.
5494 {
5495 VelocityTracker::Position positions[MAX_POINTERS];
5496 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005497 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005498 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005499 const RawPointerData::Pointer& pointer =
5500 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005501 positions[count].x = pointer.x * mPointerXMovementScale;
5502 positions[count].y = pointer.y * mPointerYMovementScale;
5503 }
5504 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005505 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 }
5507
5508 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5509 // to NEUTRAL, then we should not generate tap event.
5510 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5511 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5512 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5513 mPointerGesture.resetTap();
5514 }
5515
5516 // Pick a new active touch id if needed.
5517 // Choose an arbitrary pointer that just went down, if there is one.
5518 // Otherwise choose an arbitrary remaining pointer.
5519 // This guarantees we always have an active touch id when there is at least one pointer.
5520 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005521 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5522 int32_t activeTouchId = lastActiveTouchId;
5523 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005524 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005526 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005527 mPointerGesture.firstTouchTime = when;
5528 }
Michael Wright842500e2015-03-13 17:32:02 -07005529 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005530 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005531 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005532 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005533 } else {
5534 activeTouchId = mPointerGesture.activeTouchId = -1;
5535 }
5536 }
5537
5538 // Determine whether we are in quiet time.
5539 bool isQuietTime = false;
5540 if (activeTouchId < 0) {
5541 mPointerGesture.resetQuietTime();
5542 } else {
5543 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5544 if (!isQuietTime) {
5545 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5546 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5547 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5548 && currentFingerCount < 2) {
5549 // Enter quiet time when exiting swipe or freeform state.
5550 // This is to prevent accidentally entering the hover state and flinging the
5551 // pointer when finishing a swipe and there is still one pointer left onscreen.
5552 isQuietTime = true;
5553 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5554 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005555 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005556 // Enter quiet time when releasing the button and there are still two or more
5557 // fingers down. This may indicate that one finger was used to press the button
5558 // but it has not gone up yet.
5559 isQuietTime = true;
5560 }
5561 if (isQuietTime) {
5562 mPointerGesture.quietTime = when;
5563 }
5564 }
5565 }
5566
5567 // Switch states based on button and pointer state.
5568 if (isQuietTime) {
5569 // Case 1: Quiet time. (QUIET)
5570#if DEBUG_GESTURES
5571 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5572 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5573#endif
5574 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5575 *outFinishPreviousGesture = true;
5576 }
5577
5578 mPointerGesture.activeGestureId = -1;
5579 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5580 mPointerGesture.currentGestureIdBits.clear();
5581
5582 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005583 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005584 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5585 // The pointer follows the active touch point.
5586 // Emit DOWN, MOVE, UP events at the pointer location.
5587 //
5588 // Only the active touch matters; other fingers are ignored. This policy helps
5589 // to handle the case where the user places a second finger on the touch pad
5590 // to apply the necessary force to depress an integrated button below the surface.
5591 // We don't want the second finger to be delivered to applications.
5592 //
5593 // For this to work well, we need to make sure to track the pointer that is really
5594 // active. If the user first puts one finger down to click then adds another
5595 // finger to drag then the active pointer should switch to the finger that is
5596 // being dragged.
5597#if DEBUG_GESTURES
5598 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5599 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5600#endif
5601 // Reset state when just starting.
5602 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5603 *outFinishPreviousGesture = true;
5604 mPointerGesture.activeGestureId = 0;
5605 }
5606
5607 // Switch pointers if needed.
5608 // Find the fastest pointer and follow it.
5609 if (activeTouchId >= 0 && currentFingerCount > 1) {
5610 int32_t bestId = -1;
5611 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005612 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005613 uint32_t id = idBits.clearFirstMarkedBit();
5614 float vx, vy;
5615 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5616 float speed = hypotf(vx, vy);
5617 if (speed > bestSpeed) {
5618 bestId = id;
5619 bestSpeed = speed;
5620 }
5621 }
5622 }
5623 if (bestId >= 0 && bestId != activeTouchId) {
5624 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005625#if DEBUG_GESTURES
5626 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5627 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5628#endif
5629 }
5630 }
5631
Jun Mukaifa1706a2015-12-03 01:14:46 -08005632 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005633 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005635 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005637 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005638 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5639 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640
5641 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5642 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5643
5644 // Move the pointer using a relative motion.
5645 // When using spots, the click will occur at the position of the anchor
5646 // spot and all other spots will move there.
5647 mPointerController->move(deltaX, deltaY);
5648 } else {
5649 mPointerVelocityControl.reset();
5650 }
5651
5652 float x, y;
5653 mPointerController->getPosition(&x, &y);
5654
5655 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5656 mPointerGesture.currentGestureIdBits.clear();
5657 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5658 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5659 mPointerGesture.currentGestureProperties[0].clear();
5660 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5661 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5662 mPointerGesture.currentGestureCoords[0].clear();
5663 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5664 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5665 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5666 } else if (currentFingerCount == 0) {
5667 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5668 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5669 *outFinishPreviousGesture = true;
5670 }
5671
5672 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5673 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5674 bool tapped = false;
5675 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5676 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5677 && lastFingerCount == 1) {
5678 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5679 float x, y;
5680 mPointerController->getPosition(&x, &y);
5681 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5682 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5683#if DEBUG_GESTURES
5684 ALOGD("Gestures: TAP");
5685#endif
5686
5687 mPointerGesture.tapUpTime = when;
5688 getContext()->requestTimeoutAtTime(when
5689 + mConfig.pointerGestureTapDragInterval);
5690
5691 mPointerGesture.activeGestureId = 0;
5692 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5693 mPointerGesture.currentGestureIdBits.clear();
5694 mPointerGesture.currentGestureIdBits.markBit(
5695 mPointerGesture.activeGestureId);
5696 mPointerGesture.currentGestureIdToIndex[
5697 mPointerGesture.activeGestureId] = 0;
5698 mPointerGesture.currentGestureProperties[0].clear();
5699 mPointerGesture.currentGestureProperties[0].id =
5700 mPointerGesture.activeGestureId;
5701 mPointerGesture.currentGestureProperties[0].toolType =
5702 AMOTION_EVENT_TOOL_TYPE_FINGER;
5703 mPointerGesture.currentGestureCoords[0].clear();
5704 mPointerGesture.currentGestureCoords[0].setAxisValue(
5705 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5706 mPointerGesture.currentGestureCoords[0].setAxisValue(
5707 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5708 mPointerGesture.currentGestureCoords[0].setAxisValue(
5709 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5710
5711 tapped = true;
5712 } else {
5713#if DEBUG_GESTURES
5714 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5715 x - mPointerGesture.tapX,
5716 y - mPointerGesture.tapY);
5717#endif
5718 }
5719 } else {
5720#if DEBUG_GESTURES
5721 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5722 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5723 (when - mPointerGesture.tapDownTime) * 0.000001f);
5724 } else {
5725 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5726 }
5727#endif
5728 }
5729 }
5730
5731 mPointerVelocityControl.reset();
5732
5733 if (!tapped) {
5734#if DEBUG_GESTURES
5735 ALOGD("Gestures: NEUTRAL");
5736#endif
5737 mPointerGesture.activeGestureId = -1;
5738 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5739 mPointerGesture.currentGestureIdBits.clear();
5740 }
5741 } else if (currentFingerCount == 1) {
5742 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5743 // The pointer follows the active touch point.
5744 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5745 // When in TAP_DRAG, emit MOVE events at the pointer location.
5746 ALOG_ASSERT(activeTouchId >= 0);
5747
5748 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5749 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5750 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5751 float x, y;
5752 mPointerController->getPosition(&x, &y);
5753 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5754 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5755 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5756 } else {
5757#if DEBUG_GESTURES
5758 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5759 x - mPointerGesture.tapX,
5760 y - mPointerGesture.tapY);
5761#endif
5762 }
5763 } else {
5764#if DEBUG_GESTURES
5765 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5766 (when - mPointerGesture.tapUpTime) * 0.000001f);
5767#endif
5768 }
5769 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5770 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5771 }
5772
Jun Mukaifa1706a2015-12-03 01:14:46 -08005773 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005774 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005775 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005776 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005778 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005779 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5780 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005781
5782 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5783 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5784
5785 // Move the pointer using a relative motion.
5786 // When using spots, the hover or drag will occur at the position of the anchor spot.
5787 mPointerController->move(deltaX, deltaY);
5788 } else {
5789 mPointerVelocityControl.reset();
5790 }
5791
5792 bool down;
5793 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5794#if DEBUG_GESTURES
5795 ALOGD("Gestures: TAP_DRAG");
5796#endif
5797 down = true;
5798 } else {
5799#if DEBUG_GESTURES
5800 ALOGD("Gestures: HOVER");
5801#endif
5802 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5803 *outFinishPreviousGesture = true;
5804 }
5805 mPointerGesture.activeGestureId = 0;
5806 down = false;
5807 }
5808
5809 float x, y;
5810 mPointerController->getPosition(&x, &y);
5811
5812 mPointerGesture.currentGestureIdBits.clear();
5813 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5814 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5815 mPointerGesture.currentGestureProperties[0].clear();
5816 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5817 mPointerGesture.currentGestureProperties[0].toolType =
5818 AMOTION_EVENT_TOOL_TYPE_FINGER;
5819 mPointerGesture.currentGestureCoords[0].clear();
5820 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5821 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5822 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5823 down ? 1.0f : 0.0f);
5824
5825 if (lastFingerCount == 0 && currentFingerCount != 0) {
5826 mPointerGesture.resetTap();
5827 mPointerGesture.tapDownTime = when;
5828 mPointerGesture.tapX = x;
5829 mPointerGesture.tapY = y;
5830 }
5831 } else {
5832 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5833 // We need to provide feedback for each finger that goes down so we cannot wait
5834 // for the fingers to move before deciding what to do.
5835 //
5836 // The ambiguous case is deciding what to do when there are two fingers down but they
5837 // have not moved enough to determine whether they are part of a drag or part of a
5838 // freeform gesture, or just a press or long-press at the pointer location.
5839 //
5840 // When there are two fingers we start with the PRESS hypothesis and we generate a
5841 // down at the pointer location.
5842 //
5843 // When the two fingers move enough or when additional fingers are added, we make
5844 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5845 ALOG_ASSERT(activeTouchId >= 0);
5846
5847 bool settled = when >= mPointerGesture.firstTouchTime
5848 + mConfig.pointerGestureMultitouchSettleInterval;
5849 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5850 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5851 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5852 *outFinishPreviousGesture = true;
5853 } else if (!settled && currentFingerCount > lastFingerCount) {
5854 // Additional pointers have gone down but not yet settled.
5855 // Reset the gesture.
5856#if DEBUG_GESTURES
5857 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5858 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5859 + mConfig.pointerGestureMultitouchSettleInterval - when)
5860 * 0.000001f);
5861#endif
5862 *outCancelPreviousGesture = true;
5863 } else {
5864 // Continue previous gesture.
5865 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5866 }
5867
5868 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5869 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5870 mPointerGesture.activeGestureId = 0;
5871 mPointerGesture.referenceIdBits.clear();
5872 mPointerVelocityControl.reset();
5873
5874 // Use the centroid and pointer location as the reference points for the gesture.
5875#if DEBUG_GESTURES
5876 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5877 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5878 + mConfig.pointerGestureMultitouchSettleInterval - when)
5879 * 0.000001f);
5880#endif
Michael Wright842500e2015-03-13 17:32:02 -07005881 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005882 &mPointerGesture.referenceTouchX,
5883 &mPointerGesture.referenceTouchY);
5884 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5885 &mPointerGesture.referenceGestureY);
5886 }
5887
5888 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005889 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005890 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5891 uint32_t id = idBits.clearFirstMarkedBit();
5892 mPointerGesture.referenceDeltas[id].dx = 0;
5893 mPointerGesture.referenceDeltas[id].dy = 0;
5894 }
Michael Wright842500e2015-03-13 17:32:02 -07005895 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896
5897 // Add delta for all fingers and calculate a common movement delta.
5898 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005899 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5900 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5902 bool first = (idBits == commonIdBits);
5903 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005904 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5905 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5907 delta.dx += cpd.x - lpd.x;
5908 delta.dy += cpd.y - lpd.y;
5909
5910 if (first) {
5911 commonDeltaX = delta.dx;
5912 commonDeltaY = delta.dy;
5913 } else {
5914 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5915 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5916 }
5917 }
5918
5919 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5920 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5921 float dist[MAX_POINTER_ID + 1];
5922 int32_t distOverThreshold = 0;
5923 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5924 uint32_t id = idBits.clearFirstMarkedBit();
5925 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5926 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5927 delta.dy * mPointerYZoomScale);
5928 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5929 distOverThreshold += 1;
5930 }
5931 }
5932
5933 // Only transition when at least two pointers have moved further than
5934 // the minimum distance threshold.
5935 if (distOverThreshold >= 2) {
5936 if (currentFingerCount > 2) {
5937 // There are more than two pointers, switch to FREEFORM.
5938#if DEBUG_GESTURES
5939 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5940 currentFingerCount);
5941#endif
5942 *outCancelPreviousGesture = true;
5943 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5944 } else {
5945 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005946 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005947 uint32_t id1 = idBits.clearFirstMarkedBit();
5948 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005949 const RawPointerData::Pointer& p1 =
5950 mCurrentRawState.rawPointerData.pointerForId(id1);
5951 const RawPointerData::Pointer& p2 =
5952 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005953 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5954 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5955 // There are two pointers but they are too far apart for a SWIPE,
5956 // switch to FREEFORM.
5957#if DEBUG_GESTURES
5958 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5959 mutualDistance, mPointerGestureMaxSwipeWidth);
5960#endif
5961 *outCancelPreviousGesture = true;
5962 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5963 } else {
5964 // There are two pointers. Wait for both pointers to start moving
5965 // before deciding whether this is a SWIPE or FREEFORM gesture.
5966 float dist1 = dist[id1];
5967 float dist2 = dist[id2];
5968 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5969 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5970 // Calculate the dot product of the displacement vectors.
5971 // When the vectors are oriented in approximately the same direction,
5972 // the angle betweeen them is near zero and the cosine of the angle
5973 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5974 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5975 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5976 float dx1 = delta1.dx * mPointerXZoomScale;
5977 float dy1 = delta1.dy * mPointerYZoomScale;
5978 float dx2 = delta2.dx * mPointerXZoomScale;
5979 float dy2 = delta2.dy * mPointerYZoomScale;
5980 float dot = dx1 * dx2 + dy1 * dy2;
5981 float cosine = dot / (dist1 * dist2); // denominator always > 0
5982 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5983 // Pointers are moving in the same direction. Switch to SWIPE.
5984#if DEBUG_GESTURES
5985 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5986 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5987 "cosine %0.3f >= %0.3f",
5988 dist1, mConfig.pointerGestureMultitouchMinDistance,
5989 dist2, mConfig.pointerGestureMultitouchMinDistance,
5990 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5991#endif
5992 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5993 } else {
5994 // Pointers are moving in different directions. Switch to FREEFORM.
5995#if DEBUG_GESTURES
5996 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5997 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5998 "cosine %0.3f < %0.3f",
5999 dist1, mConfig.pointerGestureMultitouchMinDistance,
6000 dist2, mConfig.pointerGestureMultitouchMinDistance,
6001 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6002#endif
6003 *outCancelPreviousGesture = true;
6004 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6005 }
6006 }
6007 }
6008 }
6009 }
6010 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6011 // Switch from SWIPE to FREEFORM if additional pointers go down.
6012 // Cancel previous gesture.
6013 if (currentFingerCount > 2) {
6014#if DEBUG_GESTURES
6015 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6016 currentFingerCount);
6017#endif
6018 *outCancelPreviousGesture = true;
6019 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6020 }
6021 }
6022
6023 // Move the reference points based on the overall group motion of the fingers
6024 // except in PRESS mode while waiting for a transition to occur.
6025 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6026 && (commonDeltaX || commonDeltaY)) {
6027 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6028 uint32_t id = idBits.clearFirstMarkedBit();
6029 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6030 delta.dx = 0;
6031 delta.dy = 0;
6032 }
6033
6034 mPointerGesture.referenceTouchX += commonDeltaX;
6035 mPointerGesture.referenceTouchY += commonDeltaY;
6036
6037 commonDeltaX *= mPointerXMovementScale;
6038 commonDeltaY *= mPointerYMovementScale;
6039
6040 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6041 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6042
6043 mPointerGesture.referenceGestureX += commonDeltaX;
6044 mPointerGesture.referenceGestureY += commonDeltaY;
6045 }
6046
6047 // Report gestures.
6048 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6049 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6050 // PRESS or SWIPE mode.
6051#if DEBUG_GESTURES
6052 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6053 "activeGestureId=%d, currentTouchPointerCount=%d",
6054 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6055#endif
6056 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6057
6058 mPointerGesture.currentGestureIdBits.clear();
6059 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6060 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6061 mPointerGesture.currentGestureProperties[0].clear();
6062 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6063 mPointerGesture.currentGestureProperties[0].toolType =
6064 AMOTION_EVENT_TOOL_TYPE_FINGER;
6065 mPointerGesture.currentGestureCoords[0].clear();
6066 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6067 mPointerGesture.referenceGestureX);
6068 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6069 mPointerGesture.referenceGestureY);
6070 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6071 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6072 // FREEFORM mode.
6073#if DEBUG_GESTURES
6074 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6075 "activeGestureId=%d, currentTouchPointerCount=%d",
6076 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6077#endif
6078 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6079
6080 mPointerGesture.currentGestureIdBits.clear();
6081
6082 BitSet32 mappedTouchIdBits;
6083 BitSet32 usedGestureIdBits;
6084 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6085 // Initially, assign the active gesture id to the active touch point
6086 // if there is one. No other touch id bits are mapped yet.
6087 if (!*outCancelPreviousGesture) {
6088 mappedTouchIdBits.markBit(activeTouchId);
6089 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6090 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6091 mPointerGesture.activeGestureId;
6092 } else {
6093 mPointerGesture.activeGestureId = -1;
6094 }
6095 } else {
6096 // Otherwise, assume we mapped all touches from the previous frame.
6097 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006098 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6099 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006100 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6101
6102 // Check whether we need to choose a new active gesture id because the
6103 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006104 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6105 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006106 !upTouchIdBits.isEmpty(); ) {
6107 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6108 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6109 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6110 mPointerGesture.activeGestureId = -1;
6111 break;
6112 }
6113 }
6114 }
6115
6116#if DEBUG_GESTURES
6117 ALOGD("Gestures: FREEFORM follow up "
6118 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6119 "activeGestureId=%d",
6120 mappedTouchIdBits.value, usedGestureIdBits.value,
6121 mPointerGesture.activeGestureId);
6122#endif
6123
Michael Wright842500e2015-03-13 17:32:02 -07006124 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006125 for (uint32_t i = 0; i < currentFingerCount; i++) {
6126 uint32_t touchId = idBits.clearFirstMarkedBit();
6127 uint32_t gestureId;
6128 if (!mappedTouchIdBits.hasBit(touchId)) {
6129 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6130 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6131#if DEBUG_GESTURES
6132 ALOGD("Gestures: FREEFORM "
6133 "new mapping for touch id %d -> gesture id %d",
6134 touchId, gestureId);
6135#endif
6136 } else {
6137 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6138#if DEBUG_GESTURES
6139 ALOGD("Gestures: FREEFORM "
6140 "existing mapping for touch id %d -> gesture id %d",
6141 touchId, gestureId);
6142#endif
6143 }
6144 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6145 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6146
6147 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006148 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006149 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6150 * mPointerXZoomScale;
6151 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6152 * mPointerYZoomScale;
6153 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6154
6155 mPointerGesture.currentGestureProperties[i].clear();
6156 mPointerGesture.currentGestureProperties[i].id = gestureId;
6157 mPointerGesture.currentGestureProperties[i].toolType =
6158 AMOTION_EVENT_TOOL_TYPE_FINGER;
6159 mPointerGesture.currentGestureCoords[i].clear();
6160 mPointerGesture.currentGestureCoords[i].setAxisValue(
6161 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6162 mPointerGesture.currentGestureCoords[i].setAxisValue(
6163 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6164 mPointerGesture.currentGestureCoords[i].setAxisValue(
6165 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6166 }
6167
6168 if (mPointerGesture.activeGestureId < 0) {
6169 mPointerGesture.activeGestureId =
6170 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6171#if DEBUG_GESTURES
6172 ALOGD("Gestures: FREEFORM new "
6173 "activeGestureId=%d", mPointerGesture.activeGestureId);
6174#endif
6175 }
6176 }
6177 }
6178
Michael Wright842500e2015-03-13 17:32:02 -07006179 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180
6181#if DEBUG_GESTURES
6182 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6183 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6184 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6185 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6186 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6187 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6188 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6189 uint32_t id = idBits.clearFirstMarkedBit();
6190 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6191 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6192 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6193 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6194 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6195 id, index, properties.toolType,
6196 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6197 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6198 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6199 }
6200 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6201 uint32_t id = idBits.clearFirstMarkedBit();
6202 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6203 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6204 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6205 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6206 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6207 id, index, properties.toolType,
6208 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6209 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6210 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6211 }
6212#endif
6213 return true;
6214}
6215
6216void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6217 mPointerSimple.currentCoords.clear();
6218 mPointerSimple.currentProperties.clear();
6219
6220 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006221 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6222 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6223 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6224 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6225 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 mPointerController->setPosition(x, y);
6227
Michael Wright842500e2015-03-13 17:32:02 -07006228 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006229 down = !hovering;
6230
6231 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006232 mPointerSimple.currentCoords.copyFrom(
6233 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6235 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6236 mPointerSimple.currentProperties.id = 0;
6237 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006238 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 } else {
6240 down = false;
6241 hovering = false;
6242 }
6243
6244 dispatchPointerSimple(when, policyFlags, down, hovering);
6245}
6246
6247void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6248 abortPointerSimple(when, policyFlags);
6249}
6250
6251void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6252 mPointerSimple.currentCoords.clear();
6253 mPointerSimple.currentProperties.clear();
6254
6255 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006256 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6257 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6258 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006259 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006260 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6261 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006262 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006263 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006264 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006265 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006266 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006267 * mPointerYMovementScale;
6268
6269 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6270 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6271
6272 mPointerController->move(deltaX, deltaY);
6273 } else {
6274 mPointerVelocityControl.reset();
6275 }
6276
Michael Wright842500e2015-03-13 17:32:02 -07006277 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 hovering = !down;
6279
6280 float x, y;
6281 mPointerController->getPosition(&x, &y);
6282 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006283 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006284 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6285 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6286 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6287 hovering ? 0.0f : 1.0f);
6288 mPointerSimple.currentProperties.id = 0;
6289 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006290 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006291 } else {
6292 mPointerVelocityControl.reset();
6293
6294 down = false;
6295 hovering = false;
6296 }
6297
6298 dispatchPointerSimple(when, policyFlags, down, hovering);
6299}
6300
6301void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6302 abortPointerSimple(when, policyFlags);
6303
6304 mPointerVelocityControl.reset();
6305}
6306
6307void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6308 bool down, bool hovering) {
6309 int32_t metaState = getContext()->getGlobalMetaState();
Andrii Kulian620f6d92018-09-14 16:51:59 -07006310 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006311
Yi Kong9b14ac62018-07-17 13:48:38 -07006312 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 if (down || hovering) {
6314 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6315 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006316 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6318 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6319 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6320 }
Andrii Kulian620f6d92018-09-14 16:51:59 -07006321 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006322 }
6323
6324 if (mPointerSimple.down && !down) {
6325 mPointerSimple.down = false;
6326
6327 // Send up.
Prabir Pradhan42611e02018-11-27 14:04:02 -08006328 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6329 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006330 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006331 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006332 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6333 mOrientedXPrecision, mOrientedYPrecision,
6334 mPointerSimple.downTime);
6335 getListener()->notifyMotion(&args);
6336 }
6337
6338 if (mPointerSimple.hovering && !hovering) {
6339 mPointerSimple.hovering = false;
6340
6341 // Send hover exit.
Prabir Pradhan42611e02018-11-27 14:04:02 -08006342 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6343 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006344 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006345 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006346 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6347 mOrientedXPrecision, mOrientedYPrecision,
6348 mPointerSimple.downTime);
6349 getListener()->notifyMotion(&args);
6350 }
6351
6352 if (down) {
6353 if (!mPointerSimple.down) {
6354 mPointerSimple.down = true;
6355 mPointerSimple.downTime = when;
6356
6357 // Send down.
Prabir Pradhan42611e02018-11-27 14:04:02 -08006358 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6359 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006360 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006361 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006362 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6363 mOrientedXPrecision, mOrientedYPrecision,
6364 mPointerSimple.downTime);
6365 getListener()->notifyMotion(&args);
6366 }
6367
6368 // Send move.
Prabir Pradhan42611e02018-11-27 14:04:02 -08006369 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6370 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006371 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006372 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006373 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6374 mOrientedXPrecision, mOrientedYPrecision,
6375 mPointerSimple.downTime);
6376 getListener()->notifyMotion(&args);
6377 }
6378
6379 if (hovering) {
6380 if (!mPointerSimple.hovering) {
6381 mPointerSimple.hovering = true;
6382
6383 // Send hover enter.
Prabir Pradhan42611e02018-11-27 14:04:02 -08006384 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6385 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006386 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006387 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006388 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006389 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6390 mOrientedXPrecision, mOrientedYPrecision,
6391 mPointerSimple.downTime);
6392 getListener()->notifyMotion(&args);
6393 }
6394
6395 // Send hover move.
Prabir Pradhan42611e02018-11-27 14:04:02 -08006396 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6397 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006398 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006399 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006400 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6402 mOrientedXPrecision, mOrientedYPrecision,
6403 mPointerSimple.downTime);
6404 getListener()->notifyMotion(&args);
6405 }
6406
Michael Wright842500e2015-03-13 17:32:02 -07006407 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6408 float vscroll = mCurrentRawState.rawVScroll;
6409 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006410 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6411 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006412
6413 // Send scroll.
6414 PointerCoords pointerCoords;
6415 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6416 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6417 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6418
Prabir Pradhan42611e02018-11-27 14:04:02 -08006419 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6420 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006421 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006422 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006423 1, &mPointerSimple.currentProperties, &pointerCoords,
6424 mOrientedXPrecision, mOrientedYPrecision,
6425 mPointerSimple.downTime);
6426 getListener()->notifyMotion(&args);
6427 }
6428
6429 // Save state.
6430 if (down || hovering) {
6431 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6432 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6433 } else {
6434 mPointerSimple.reset();
6435 }
6436}
6437
6438void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6439 mPointerSimple.currentCoords.clear();
6440 mPointerSimple.currentProperties.clear();
6441
6442 dispatchPointerSimple(when, policyFlags, false, false);
6443}
6444
6445void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006446 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006447 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006448 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006449 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6450 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451 PointerCoords pointerCoords[MAX_POINTERS];
6452 PointerProperties pointerProperties[MAX_POINTERS];
6453 uint32_t pointerCount = 0;
6454 while (!idBits.isEmpty()) {
6455 uint32_t id = idBits.clearFirstMarkedBit();
6456 uint32_t index = idToIndex[id];
6457 pointerProperties[pointerCount].copyFrom(properties[index]);
6458 pointerCoords[pointerCount].copyFrom(coords[index]);
6459
6460 if (changedId >= 0 && id == uint32_t(changedId)) {
6461 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6462 }
6463
6464 pointerCount += 1;
6465 }
6466
6467 ALOG_ASSERT(pointerCount != 0);
6468
6469 if (changedId >= 0 && pointerCount == 1) {
6470 // Replace initial down and final up action.
6471 // We can compare the action without masking off the changed pointer index
6472 // because we know the index is 0.
6473 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6474 action = AMOTION_EVENT_ACTION_DOWN;
6475 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6476 action = AMOTION_EVENT_ACTION_UP;
6477 } else {
6478 // Can't happen.
6479 ALOG_ASSERT(false);
6480 }
6481 }
Andrii Kulian620f6d92018-09-14 16:51:59 -07006482 int32_t displayId = mPointerController != nullptr ?
6483 mPointerController->getDisplayId() : mViewport.displayId;
Prabir Pradhan42611e02018-11-27 14:04:02 -08006484 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6485 source, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006486 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006487 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006488 xPrecision, yPrecision, downTime);
6489 getListener()->notifyMotion(&args);
6490}
6491
6492bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6493 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6494 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6495 BitSet32 idBits) const {
6496 bool changed = false;
6497 while (!idBits.isEmpty()) {
6498 uint32_t id = idBits.clearFirstMarkedBit();
6499 uint32_t inIndex = inIdToIndex[id];
6500 uint32_t outIndex = outIdToIndex[id];
6501
6502 const PointerProperties& curInProperties = inProperties[inIndex];
6503 const PointerCoords& curInCoords = inCoords[inIndex];
6504 PointerProperties& curOutProperties = outProperties[outIndex];
6505 PointerCoords& curOutCoords = outCoords[outIndex];
6506
6507 if (curInProperties != curOutProperties) {
6508 curOutProperties.copyFrom(curInProperties);
6509 changed = true;
6510 }
6511
6512 if (curInCoords != curOutCoords) {
6513 curOutCoords.copyFrom(curInCoords);
6514 changed = true;
6515 }
6516 }
6517 return changed;
6518}
6519
6520void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006521 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006522 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6523 }
6524}
6525
Jeff Brownc9aa6282015-02-11 19:03:28 -08006526void TouchInputMapper::cancelTouch(nsecs_t when) {
6527 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006528 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006529}
6530
Michael Wrightd02c5b62014-02-10 15:10:22 -08006531bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006532 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006533 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006534 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006535 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6536 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6537 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006538}
6539
6540const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6541 int32_t x, int32_t y) {
6542 size_t numVirtualKeys = mVirtualKeys.size();
6543 for (size_t i = 0; i < numVirtualKeys; i++) {
6544 const VirtualKey& virtualKey = mVirtualKeys[i];
6545
6546#if DEBUG_VIRTUAL_KEYS
6547 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6548 "left=%d, top=%d, right=%d, bottom=%d",
6549 x, y,
6550 virtualKey.keyCode, virtualKey.scanCode,
6551 virtualKey.hitLeft, virtualKey.hitTop,
6552 virtualKey.hitRight, virtualKey.hitBottom);
6553#endif
6554
6555 if (virtualKey.isHit(x, y)) {
6556 return & virtualKey;
6557 }
6558 }
6559
Yi Kong9b14ac62018-07-17 13:48:38 -07006560 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006561}
6562
Michael Wright842500e2015-03-13 17:32:02 -07006563void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6564 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6565 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006566
Michael Wright842500e2015-03-13 17:32:02 -07006567 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006568
6569 if (currentPointerCount == 0) {
6570 // No pointers to assign.
6571 return;
6572 }
6573
6574 if (lastPointerCount == 0) {
6575 // All pointers are new.
6576 for (uint32_t i = 0; i < currentPointerCount; i++) {
6577 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006578 current->rawPointerData.pointers[i].id = id;
6579 current->rawPointerData.idToIndex[id] = i;
6580 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006581 }
6582 return;
6583 }
6584
6585 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006586 && current->rawPointerData.pointers[0].toolType
6587 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006588 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006589 uint32_t id = last->rawPointerData.pointers[0].id;
6590 current->rawPointerData.pointers[0].id = id;
6591 current->rawPointerData.idToIndex[id] = 0;
6592 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006593 return;
6594 }
6595
6596 // General case.
6597 // We build a heap of squared euclidean distances between current and last pointers
6598 // associated with the current and last pointer indices. Then, we find the best
6599 // match (by distance) for each current pointer.
6600 // The pointers must have the same tool type but it is possible for them to
6601 // transition from hovering to touching or vice-versa while retaining the same id.
6602 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6603
6604 uint32_t heapSize = 0;
6605 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6606 currentPointerIndex++) {
6607 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6608 lastPointerIndex++) {
6609 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006610 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006611 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006612 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006613 if (currentPointer.toolType == lastPointer.toolType) {
6614 int64_t deltaX = currentPointer.x - lastPointer.x;
6615 int64_t deltaY = currentPointer.y - lastPointer.y;
6616
6617 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6618
6619 // Insert new element into the heap (sift up).
6620 heap[heapSize].currentPointerIndex = currentPointerIndex;
6621 heap[heapSize].lastPointerIndex = lastPointerIndex;
6622 heap[heapSize].distance = distance;
6623 heapSize += 1;
6624 }
6625 }
6626 }
6627
6628 // Heapify
6629 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6630 startIndex -= 1;
6631 for (uint32_t parentIndex = startIndex; ;) {
6632 uint32_t childIndex = parentIndex * 2 + 1;
6633 if (childIndex >= heapSize) {
6634 break;
6635 }
6636
6637 if (childIndex + 1 < heapSize
6638 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6639 childIndex += 1;
6640 }
6641
6642 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6643 break;
6644 }
6645
6646 swap(heap[parentIndex], heap[childIndex]);
6647 parentIndex = childIndex;
6648 }
6649 }
6650
6651#if DEBUG_POINTER_ASSIGNMENT
6652 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6653 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006654 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006655 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6656 heap[i].distance);
6657 }
6658#endif
6659
6660 // Pull matches out by increasing order of distance.
6661 // To avoid reassigning pointers that have already been matched, the loop keeps track
6662 // of which last and current pointers have been matched using the matchedXXXBits variables.
6663 // It also tracks the used pointer id bits.
6664 BitSet32 matchedLastBits(0);
6665 BitSet32 matchedCurrentBits(0);
6666 BitSet32 usedIdBits(0);
6667 bool first = true;
6668 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6669 while (heapSize > 0) {
6670 if (first) {
6671 // The first time through the loop, we just consume the root element of
6672 // the heap (the one with smallest distance).
6673 first = false;
6674 } else {
6675 // Previous iterations consumed the root element of the heap.
6676 // Pop root element off of the heap (sift down).
6677 heap[0] = heap[heapSize];
6678 for (uint32_t parentIndex = 0; ;) {
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#if DEBUG_POINTER_ASSIGNMENT
6698 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6699 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006700 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006701 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6702 heap[i].distance);
6703 }
6704#endif
6705 }
6706
6707 heapSize -= 1;
6708
6709 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6710 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6711
6712 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6713 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6714
6715 matchedCurrentBits.markBit(currentPointerIndex);
6716 matchedLastBits.markBit(lastPointerIndex);
6717
Michael Wright842500e2015-03-13 17:32:02 -07006718 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6719 current->rawPointerData.pointers[currentPointerIndex].id = id;
6720 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6721 current->rawPointerData.markIdBit(id,
6722 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006723 usedIdBits.markBit(id);
6724
6725#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006726 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6727 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006728 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6729#endif
6730 break;
6731 }
6732 }
6733
6734 // Assign fresh ids to pointers that were not matched in the process.
6735 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6736 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6737 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6738
Michael Wright842500e2015-03-13 17:32:02 -07006739 current->rawPointerData.pointers[currentPointerIndex].id = id;
6740 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6741 current->rawPointerData.markIdBit(id,
6742 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006743
6744#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006745 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006746#endif
6747 }
6748}
6749
6750int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6751 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6752 return AKEY_STATE_VIRTUAL;
6753 }
6754
6755 size_t numVirtualKeys = mVirtualKeys.size();
6756 for (size_t i = 0; i < numVirtualKeys; i++) {
6757 const VirtualKey& virtualKey = mVirtualKeys[i];
6758 if (virtualKey.keyCode == keyCode) {
6759 return AKEY_STATE_UP;
6760 }
6761 }
6762
6763 return AKEY_STATE_UNKNOWN;
6764}
6765
6766int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6767 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6768 return AKEY_STATE_VIRTUAL;
6769 }
6770
6771 size_t numVirtualKeys = mVirtualKeys.size();
6772 for (size_t i = 0; i < numVirtualKeys; i++) {
6773 const VirtualKey& virtualKey = mVirtualKeys[i];
6774 if (virtualKey.scanCode == scanCode) {
6775 return AKEY_STATE_UP;
6776 }
6777 }
6778
6779 return AKEY_STATE_UNKNOWN;
6780}
6781
6782bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6783 const int32_t* keyCodes, uint8_t* outFlags) {
6784 size_t numVirtualKeys = mVirtualKeys.size();
6785 for (size_t i = 0; i < numVirtualKeys; i++) {
6786 const VirtualKey& virtualKey = mVirtualKeys[i];
6787
6788 for (size_t i = 0; i < numCodes; i++) {
6789 if (virtualKey.keyCode == keyCodes[i]) {
6790 outFlags[i] = 1;
6791 }
6792 }
6793 }
6794
6795 return true;
6796}
6797
6798
6799// --- SingleTouchInputMapper ---
6800
6801SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6802 TouchInputMapper(device) {
6803}
6804
6805SingleTouchInputMapper::~SingleTouchInputMapper() {
6806}
6807
6808void SingleTouchInputMapper::reset(nsecs_t when) {
6809 mSingleTouchMotionAccumulator.reset(getDevice());
6810
6811 TouchInputMapper::reset(when);
6812}
6813
6814void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6815 TouchInputMapper::process(rawEvent);
6816
6817 mSingleTouchMotionAccumulator.process(rawEvent);
6818}
6819
Michael Wright842500e2015-03-13 17:32:02 -07006820void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006821 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006822 outState->rawPointerData.pointerCount = 1;
6823 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006824
6825 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6826 && (mTouchButtonAccumulator.isHovering()
6827 || (mRawPointerAxes.pressure.valid
6828 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006829 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006830
Michael Wright842500e2015-03-13 17:32:02 -07006831 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006832 outPointer.id = 0;
6833 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6834 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6835 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6836 outPointer.touchMajor = 0;
6837 outPointer.touchMinor = 0;
6838 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6839 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6840 outPointer.orientation = 0;
6841 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6842 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6843 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6844 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6845 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6846 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6847 }
6848 outPointer.isHovering = isHovering;
6849 }
6850}
6851
6852void SingleTouchInputMapper::configureRawPointerAxes() {
6853 TouchInputMapper::configureRawPointerAxes();
6854
6855 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6856 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6857 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6858 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6859 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6860 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6861 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6862}
6863
6864bool SingleTouchInputMapper::hasStylus() const {
6865 return mTouchButtonAccumulator.hasStylus();
6866}
6867
6868
6869// --- MultiTouchInputMapper ---
6870
6871MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6872 TouchInputMapper(device) {
6873}
6874
6875MultiTouchInputMapper::~MultiTouchInputMapper() {
6876}
6877
6878void MultiTouchInputMapper::reset(nsecs_t when) {
6879 mMultiTouchMotionAccumulator.reset(getDevice());
6880
6881 mPointerIdBits.clear();
6882
6883 TouchInputMapper::reset(when);
6884}
6885
6886void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6887 TouchInputMapper::process(rawEvent);
6888
6889 mMultiTouchMotionAccumulator.process(rawEvent);
6890}
6891
Michael Wright842500e2015-03-13 17:32:02 -07006892void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006893 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6894 size_t outCount = 0;
6895 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006896 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006897
6898 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6899 const MultiTouchMotionAccumulator::Slot* inSlot =
6900 mMultiTouchMotionAccumulator.getSlot(inIndex);
6901 if (!inSlot->isInUse()) {
6902 continue;
6903 }
6904
6905 if (outCount >= MAX_POINTERS) {
6906#if DEBUG_POINTERS
6907 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6908 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006909 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006910#endif
6911 break; // too many fingers!
6912 }
6913
Michael Wright842500e2015-03-13 17:32:02 -07006914 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006915 outPointer.x = inSlot->getX();
6916 outPointer.y = inSlot->getY();
6917 outPointer.pressure = inSlot->getPressure();
6918 outPointer.touchMajor = inSlot->getTouchMajor();
6919 outPointer.touchMinor = inSlot->getTouchMinor();
6920 outPointer.toolMajor = inSlot->getToolMajor();
6921 outPointer.toolMinor = inSlot->getToolMinor();
6922 outPointer.orientation = inSlot->getOrientation();
6923 outPointer.distance = inSlot->getDistance();
6924 outPointer.tiltX = 0;
6925 outPointer.tiltY = 0;
6926
6927 outPointer.toolType = inSlot->getToolType();
6928 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6929 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6930 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6931 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6932 }
6933 }
6934
6935 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6936 && (mTouchButtonAccumulator.isHovering()
6937 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6938 outPointer.isHovering = isHovering;
6939
6940 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006941 if (mHavePointerIds) {
6942 int32_t trackingId = inSlot->getTrackingId();
6943 int32_t id = -1;
6944 if (trackingId >= 0) {
6945 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6946 uint32_t n = idBits.clearFirstMarkedBit();
6947 if (mPointerTrackingIdMap[n] == trackingId) {
6948 id = n;
6949 }
6950 }
6951
6952 if (id < 0 && !mPointerIdBits.isFull()) {
6953 id = mPointerIdBits.markFirstUnmarkedBit();
6954 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006955 }
Michael Wright842500e2015-03-13 17:32:02 -07006956 }
gaoshang1a632de2016-08-24 10:23:50 +08006957 if (id < 0) {
6958 mHavePointerIds = false;
6959 outState->rawPointerData.clearIdBits();
6960 newPointerIdBits.clear();
6961 } else {
6962 outPointer.id = id;
6963 outState->rawPointerData.idToIndex[id] = outCount;
6964 outState->rawPointerData.markIdBit(id, isHovering);
6965 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006966 }
Michael Wright842500e2015-03-13 17:32:02 -07006967 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006968 outCount += 1;
6969 }
6970
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006971 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006972 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006973 mPointerIdBits = newPointerIdBits;
6974
6975 mMultiTouchMotionAccumulator.finishSync();
6976}
6977
6978void MultiTouchInputMapper::configureRawPointerAxes() {
6979 TouchInputMapper::configureRawPointerAxes();
6980
6981 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6982 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6983 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6984 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6985 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6986 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6987 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6988 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6989 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6990 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6991 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6992
6993 if (mRawPointerAxes.trackingId.valid
6994 && mRawPointerAxes.slot.valid
6995 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6996 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6997 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006998 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6999 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007000 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007001 slotCount = MAX_SLOTS;
7002 }
7003 mMultiTouchMotionAccumulator.configure(getDevice(),
7004 slotCount, true /*usingSlotsProtocol*/);
7005 } else {
7006 mMultiTouchMotionAccumulator.configure(getDevice(),
7007 MAX_POINTERS, false /*usingSlotsProtocol*/);
7008 }
7009}
7010
7011bool MultiTouchInputMapper::hasStylus() const {
7012 return mMultiTouchMotionAccumulator.hasStylus()
7013 || mTouchButtonAccumulator.hasStylus();
7014}
7015
Michael Wright842500e2015-03-13 17:32:02 -07007016// --- ExternalStylusInputMapper
7017
7018ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7019 InputMapper(device) {
7020
7021}
7022
7023uint32_t ExternalStylusInputMapper::getSources() {
7024 return AINPUT_SOURCE_STYLUS;
7025}
7026
7027void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7028 InputMapper::populateDeviceInfo(info);
7029 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7030 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7031}
7032
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007033void ExternalStylusInputMapper::dump(std::string& dump) {
7034 dump += INDENT2 "External Stylus Input Mapper:\n";
7035 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007036 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007037 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007038 dumpStylusState(dump, mStylusState);
7039}
7040
7041void ExternalStylusInputMapper::configure(nsecs_t when,
7042 const InputReaderConfiguration* config, uint32_t changes) {
7043 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7044 mTouchButtonAccumulator.configure(getDevice());
7045}
7046
7047void ExternalStylusInputMapper::reset(nsecs_t when) {
7048 InputDevice* device = getDevice();
7049 mSingleTouchMotionAccumulator.reset(device);
7050 mTouchButtonAccumulator.reset(device);
7051 InputMapper::reset(when);
7052}
7053
7054void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7055 mSingleTouchMotionAccumulator.process(rawEvent);
7056 mTouchButtonAccumulator.process(rawEvent);
7057
7058 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7059 sync(rawEvent->when);
7060 }
7061}
7062
7063void ExternalStylusInputMapper::sync(nsecs_t when) {
7064 mStylusState.clear();
7065
7066 mStylusState.when = when;
7067
Michael Wright45ccacf2015-04-21 19:01:58 +01007068 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7069 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7070 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7071 }
7072
Michael Wright842500e2015-03-13 17:32:02 -07007073 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7074 if (mRawPressureAxis.valid) {
7075 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7076 } else if (mTouchButtonAccumulator.isToolActive()) {
7077 mStylusState.pressure = 1.0f;
7078 } else {
7079 mStylusState.pressure = 0.0f;
7080 }
7081
7082 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007083
7084 mContext->dispatchExternalStylusState(mStylusState);
7085}
7086
Michael Wrightd02c5b62014-02-10 15:10:22 -08007087
7088// --- JoystickInputMapper ---
7089
7090JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7091 InputMapper(device) {
7092}
7093
7094JoystickInputMapper::~JoystickInputMapper() {
7095}
7096
7097uint32_t JoystickInputMapper::getSources() {
7098 return AINPUT_SOURCE_JOYSTICK;
7099}
7100
7101void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7102 InputMapper::populateDeviceInfo(info);
7103
7104 for (size_t i = 0; i < mAxes.size(); i++) {
7105 const Axis& axis = mAxes.valueAt(i);
7106 addMotionRange(axis.axisInfo.axis, axis, info);
7107
7108 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7109 addMotionRange(axis.axisInfo.highAxis, axis, info);
7110
7111 }
7112 }
7113}
7114
7115void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7116 InputDeviceInfo* info) {
7117 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7118 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7119 /* In order to ease the transition for developers from using the old axes
7120 * to the newer, more semantically correct axes, we'll continue to register
7121 * the old axes as duplicates of their corresponding new ones. */
7122 int32_t compatAxis = getCompatAxis(axisId);
7123 if (compatAxis >= 0) {
7124 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7125 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7126 }
7127}
7128
7129/* A mapping from axes the joystick actually has to the axes that should be
7130 * artificially created for compatibility purposes.
7131 * Returns -1 if no compatibility axis is needed. */
7132int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7133 switch(axis) {
7134 case AMOTION_EVENT_AXIS_LTRIGGER:
7135 return AMOTION_EVENT_AXIS_BRAKE;
7136 case AMOTION_EVENT_AXIS_RTRIGGER:
7137 return AMOTION_EVENT_AXIS_GAS;
7138 }
7139 return -1;
7140}
7141
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007142void JoystickInputMapper::dump(std::string& dump) {
7143 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007144
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007145 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007146 size_t numAxes = mAxes.size();
7147 for (size_t i = 0; i < numAxes; i++) {
7148 const Axis& axis = mAxes.valueAt(i);
7149 const char* label = getAxisLabel(axis.axisInfo.axis);
7150 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007151 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007152 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007153 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007154 }
7155 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7156 label = getAxisLabel(axis.axisInfo.highAxis);
7157 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007158 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007159 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007160 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007161 axis.axisInfo.splitValue);
7162 }
7163 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007164 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007165 }
7166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007167 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 -08007168 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007169 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007170 "highScale=%0.5f, highOffset=%0.5f\n",
7171 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007172 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007173 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7174 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7175 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7176 }
7177}
7178
7179void JoystickInputMapper::configure(nsecs_t when,
7180 const InputReaderConfiguration* config, uint32_t changes) {
7181 InputMapper::configure(when, config, changes);
7182
7183 if (!changes) { // first time only
7184 // Collect all axes.
7185 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7186 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7187 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7188 continue; // axis must be claimed by a different device
7189 }
7190
7191 RawAbsoluteAxisInfo rawAxisInfo;
7192 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7193 if (rawAxisInfo.valid) {
7194 // Map axis.
7195 AxisInfo axisInfo;
7196 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7197 if (!explicitlyMapped) {
7198 // Axis is not explicitly mapped, will choose a generic axis later.
7199 axisInfo.mode = AxisInfo::MODE_NORMAL;
7200 axisInfo.axis = -1;
7201 }
7202
7203 // Apply flat override.
7204 int32_t rawFlat = axisInfo.flatOverride < 0
7205 ? rawAxisInfo.flat : axisInfo.flatOverride;
7206
7207 // Calculate scaling factors and limits.
7208 Axis axis;
7209 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7210 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7211 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7212 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7213 scale, 0.0f, highScale, 0.0f,
7214 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7215 rawAxisInfo.resolution * scale);
7216 } else if (isCenteredAxis(axisInfo.axis)) {
7217 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7218 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7219 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7220 scale, offset, scale, offset,
7221 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7222 rawAxisInfo.resolution * scale);
7223 } else {
7224 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7225 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7226 scale, 0.0f, scale, 0.0f,
7227 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7228 rawAxisInfo.resolution * scale);
7229 }
7230
7231 // To eliminate noise while the joystick is at rest, filter out small variations
7232 // in axis values up front.
7233 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7234
7235 mAxes.add(abs, axis);
7236 }
7237 }
7238
7239 // If there are too many axes, start dropping them.
7240 // Prefer to keep explicitly mapped axes.
7241 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007242 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007243 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007244 pruneAxes(true);
7245 pruneAxes(false);
7246 }
7247
7248 // Assign generic axis ids to remaining axes.
7249 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7250 size_t numAxes = mAxes.size();
7251 for (size_t i = 0; i < numAxes; i++) {
7252 Axis& axis = mAxes.editValueAt(i);
7253 if (axis.axisInfo.axis < 0) {
7254 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7255 && haveAxis(nextGenericAxisId)) {
7256 nextGenericAxisId += 1;
7257 }
7258
7259 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7260 axis.axisInfo.axis = nextGenericAxisId;
7261 nextGenericAxisId += 1;
7262 } else {
7263 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7264 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007265 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007266 mAxes.removeItemsAt(i--);
7267 numAxes -= 1;
7268 }
7269 }
7270 }
7271 }
7272}
7273
7274bool JoystickInputMapper::haveAxis(int32_t axisId) {
7275 size_t numAxes = mAxes.size();
7276 for (size_t i = 0; i < numAxes; i++) {
7277 const Axis& axis = mAxes.valueAt(i);
7278 if (axis.axisInfo.axis == axisId
7279 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7280 && axis.axisInfo.highAxis == axisId)) {
7281 return true;
7282 }
7283 }
7284 return false;
7285}
7286
7287void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7288 size_t i = mAxes.size();
7289 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7290 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7291 continue;
7292 }
7293 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007294 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007295 mAxes.removeItemsAt(i);
7296 }
7297}
7298
7299bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7300 switch (axis) {
7301 case AMOTION_EVENT_AXIS_X:
7302 case AMOTION_EVENT_AXIS_Y:
7303 case AMOTION_EVENT_AXIS_Z:
7304 case AMOTION_EVENT_AXIS_RX:
7305 case AMOTION_EVENT_AXIS_RY:
7306 case AMOTION_EVENT_AXIS_RZ:
7307 case AMOTION_EVENT_AXIS_HAT_X:
7308 case AMOTION_EVENT_AXIS_HAT_Y:
7309 case AMOTION_EVENT_AXIS_ORIENTATION:
7310 case AMOTION_EVENT_AXIS_RUDDER:
7311 case AMOTION_EVENT_AXIS_WHEEL:
7312 return true;
7313 default:
7314 return false;
7315 }
7316}
7317
7318void JoystickInputMapper::reset(nsecs_t when) {
7319 // Recenter all axes.
7320 size_t numAxes = mAxes.size();
7321 for (size_t i = 0; i < numAxes; i++) {
7322 Axis& axis = mAxes.editValueAt(i);
7323 axis.resetValue();
7324 }
7325
7326 InputMapper::reset(when);
7327}
7328
7329void JoystickInputMapper::process(const RawEvent* rawEvent) {
7330 switch (rawEvent->type) {
7331 case EV_ABS: {
7332 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7333 if (index >= 0) {
7334 Axis& axis = mAxes.editValueAt(index);
7335 float newValue, highNewValue;
7336 switch (axis.axisInfo.mode) {
7337 case AxisInfo::MODE_INVERT:
7338 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7339 * axis.scale + axis.offset;
7340 highNewValue = 0.0f;
7341 break;
7342 case AxisInfo::MODE_SPLIT:
7343 if (rawEvent->value < axis.axisInfo.splitValue) {
7344 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7345 * axis.scale + axis.offset;
7346 highNewValue = 0.0f;
7347 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7348 newValue = 0.0f;
7349 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7350 * axis.highScale + axis.highOffset;
7351 } else {
7352 newValue = 0.0f;
7353 highNewValue = 0.0f;
7354 }
7355 break;
7356 default:
7357 newValue = rawEvent->value * axis.scale + axis.offset;
7358 highNewValue = 0.0f;
7359 break;
7360 }
7361 axis.newValue = newValue;
7362 axis.highNewValue = highNewValue;
7363 }
7364 break;
7365 }
7366
7367 case EV_SYN:
7368 switch (rawEvent->code) {
7369 case SYN_REPORT:
7370 sync(rawEvent->when, false /*force*/);
7371 break;
7372 }
7373 break;
7374 }
7375}
7376
7377void JoystickInputMapper::sync(nsecs_t when, bool force) {
7378 if (!filterAxes(force)) {
7379 return;
7380 }
7381
7382 int32_t metaState = mContext->getGlobalMetaState();
7383 int32_t buttonState = 0;
7384
7385 PointerProperties pointerProperties;
7386 pointerProperties.clear();
7387 pointerProperties.id = 0;
7388 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7389
7390 PointerCoords pointerCoords;
7391 pointerCoords.clear();
7392
7393 size_t numAxes = mAxes.size();
7394 for (size_t i = 0; i < numAxes; i++) {
7395 const Axis& axis = mAxes.valueAt(i);
7396 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7397 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7398 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7399 axis.highCurrentValue);
7400 }
7401 }
7402
7403 // Moving a joystick axis should not wake the device because joysticks can
7404 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7405 // button will likely wake the device.
7406 // TODO: Use the input device configuration to control this behavior more finely.
7407 uint32_t policyFlags = 0;
7408
Prabir Pradhan42611e02018-11-27 14:04:02 -08007409 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7410 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007411 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007412 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007413 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007414 getListener()->notifyMotion(&args);
7415}
7416
7417void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7418 int32_t axis, float value) {
7419 pointerCoords->setAxisValue(axis, value);
7420 /* In order to ease the transition for developers from using the old axes
7421 * to the newer, more semantically correct axes, we'll continue to produce
7422 * values for the old axes as mirrors of the value of their corresponding
7423 * new axes. */
7424 int32_t compatAxis = getCompatAxis(axis);
7425 if (compatAxis >= 0) {
7426 pointerCoords->setAxisValue(compatAxis, value);
7427 }
7428}
7429
7430bool JoystickInputMapper::filterAxes(bool force) {
7431 bool atLeastOneSignificantChange = force;
7432 size_t numAxes = mAxes.size();
7433 for (size_t i = 0; i < numAxes; i++) {
7434 Axis& axis = mAxes.editValueAt(i);
7435 if (force || hasValueChangedSignificantly(axis.filter,
7436 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7437 axis.currentValue = axis.newValue;
7438 atLeastOneSignificantChange = true;
7439 }
7440 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7441 if (force || hasValueChangedSignificantly(axis.filter,
7442 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7443 axis.highCurrentValue = axis.highNewValue;
7444 atLeastOneSignificantChange = true;
7445 }
7446 }
7447 }
7448 return atLeastOneSignificantChange;
7449}
7450
7451bool JoystickInputMapper::hasValueChangedSignificantly(
7452 float filter, float newValue, float currentValue, float min, float max) {
7453 if (newValue != currentValue) {
7454 // Filter out small changes in value unless the value is converging on the axis
7455 // bounds or center point. This is intended to reduce the amount of information
7456 // sent to applications by particularly noisy joysticks (such as PS3).
7457 if (fabs(newValue - currentValue) > filter
7458 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7459 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7460 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7461 return true;
7462 }
7463 }
7464 return false;
7465}
7466
7467bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7468 float filter, float newValue, float currentValue, float thresholdValue) {
7469 float newDistance = fabs(newValue - thresholdValue);
7470 if (newDistance < filter) {
7471 float oldDistance = fabs(currentValue - thresholdValue);
7472 if (newDistance < oldDistance) {
7473 return true;
7474 }
7475 }
7476 return false;
7477}
7478
7479} // namespace android