blob: 2b31f6e0e67acb6f661193c32f3eebdfd78adc21 [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
Michael Wrightd02c5b62014-02-10 15:10:22 -0800257// --- InputReader ---
258
259InputReader::InputReader(const sp<EventHubInterface>& eventHub,
260 const sp<InputReaderPolicyInterface>& policy,
261 const sp<InputListenerInterface>& listener) :
262 mContext(this), mEventHub(eventHub), mPolicy(policy),
Prabir Pradhan42611e02018-11-27 14:04:02 -0800263 mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800264 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
265 mConfigurationChangesToRefresh(0) {
266 mQueuedListener = new QueuedInputListener(listener);
267
268 { // acquire lock
269 AutoMutex _l(mLock);
270
271 refreshConfigurationLocked(0);
272 updateGlobalMetaStateLocked();
273 } // release lock
274}
275
276InputReader::~InputReader() {
277 for (size_t i = 0; i < mDevices.size(); i++) {
278 delete mDevices.valueAt(i);
279 }
280}
281
282void InputReader::loopOnce() {
283 int32_t oldGeneration;
284 int32_t timeoutMillis;
285 bool inputDevicesChanged = false;
286 Vector<InputDeviceInfo> inputDevices;
287 { // acquire lock
288 AutoMutex _l(mLock);
289
290 oldGeneration = mGeneration;
291 timeoutMillis = -1;
292
293 uint32_t changes = mConfigurationChangesToRefresh;
294 if (changes) {
295 mConfigurationChangesToRefresh = 0;
296 timeoutMillis = 0;
297 refreshConfigurationLocked(changes);
298 } else if (mNextTimeout != LLONG_MAX) {
299 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
300 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
301 }
302 } // release lock
303
304 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
305
306 { // acquire lock
307 AutoMutex _l(mLock);
308 mReaderIsAliveCondition.broadcast();
309
310 if (count) {
311 processEventsLocked(mEventBuffer, count);
312 }
313
314 if (mNextTimeout != LLONG_MAX) {
315 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
316 if (now >= mNextTimeout) {
317#if DEBUG_RAW_EVENTS
318 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
319#endif
320 mNextTimeout = LLONG_MAX;
321 timeoutExpiredLocked(now);
322 }
323 }
324
325 if (oldGeneration != mGeneration) {
326 inputDevicesChanged = true;
327 getInputDevicesLocked(inputDevices);
328 }
329 } // release lock
330
331 // Send out a message that the describes the changed input devices.
332 if (inputDevicesChanged) {
333 mPolicy->notifyInputDevicesChanged(inputDevices);
334 }
335
336 // Flush queued events out to the listener.
337 // This must happen outside of the lock because the listener could potentially call
338 // back into the InputReader's methods, such as getScanCodeState, or become blocked
339 // on another thread similarly waiting to acquire the InputReader lock thereby
340 // resulting in a deadlock. This situation is actually quite plausible because the
341 // listener is actually the input dispatcher, which calls into the window manager,
342 // which occasionally calls into the input reader.
343 mQueuedListener->flush();
344}
345
346void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
347 for (const RawEvent* rawEvent = rawEvents; count;) {
348 int32_t type = rawEvent->type;
349 size_t batchSize = 1;
350 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
351 int32_t deviceId = rawEvent->deviceId;
352 while (batchSize < count) {
353 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
354 || rawEvent[batchSize].deviceId != deviceId) {
355 break;
356 }
357 batchSize += 1;
358 }
359#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700360 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800361#endif
362 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
363 } else {
364 switch (rawEvent->type) {
365 case EventHubInterface::DEVICE_ADDED:
366 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
367 break;
368 case EventHubInterface::DEVICE_REMOVED:
369 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
370 break;
371 case EventHubInterface::FINISHED_DEVICE_SCAN:
372 handleConfigurationChangedLocked(rawEvent->when);
373 break;
374 default:
375 ALOG_ASSERT(false); // can't happen
376 break;
377 }
378 }
379 count -= batchSize;
380 rawEvent += batchSize;
381 }
382}
383
384void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
385 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
386 if (deviceIndex >= 0) {
387 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
388 return;
389 }
390
391 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
392 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
393 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
394
395 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
396 device->configure(when, &mConfig, 0);
397 device->reset(when);
398
399 if (device->isIgnored()) {
400 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100401 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800402 } else {
403 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100404 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800405 }
406
407 mDevices.add(deviceId, device);
408 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700409
410 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
411 notifyExternalStylusPresenceChanged();
412 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800413}
414
415void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700416 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800417 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
418 if (deviceIndex < 0) {
419 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
420 return;
421 }
422
423 device = mDevices.valueAt(deviceIndex);
424 mDevices.removeItemsAt(deviceIndex, 1);
425 bumpGenerationLocked();
426
427 if (device->isIgnored()) {
428 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100429 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800430 } else {
431 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100432 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800433 }
434
Michael Wright842500e2015-03-13 17:32:02 -0700435 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
436 notifyExternalStylusPresenceChanged();
437 }
438
Michael Wrightd02c5b62014-02-10 15:10:22 -0800439 device->reset(when);
440 delete device;
441}
442
443InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
444 const InputDeviceIdentifier& identifier, uint32_t classes) {
445 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
446 controllerNumber, identifier, classes);
447
448 // External devices.
449 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
450 device->setExternal(true);
451 }
452
Tim Kilbourn063ff532015-04-08 10:26:18 -0700453 // Devices with mics.
454 if (classes & INPUT_DEVICE_CLASS_MIC) {
455 device->setMic(true);
456 }
457
Michael Wrightd02c5b62014-02-10 15:10:22 -0800458 // Switch-like devices.
459 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
460 device->addMapper(new SwitchInputMapper(device));
461 }
462
Prashant Malani1941ff52015-08-11 18:29:28 -0700463 // Scroll wheel-like devices.
464 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
465 device->addMapper(new RotaryEncoderInputMapper(device));
466 }
467
Michael Wrightd02c5b62014-02-10 15:10:22 -0800468 // Vibrator-like devices.
469 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
470 device->addMapper(new VibratorInputMapper(device));
471 }
472
473 // Keyboard-like devices.
474 uint32_t keyboardSource = 0;
475 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
476 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
477 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
478 }
479 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
480 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
481 }
482 if (classes & INPUT_DEVICE_CLASS_DPAD) {
483 keyboardSource |= AINPUT_SOURCE_DPAD;
484 }
485 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
486 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
487 }
488
489 if (keyboardSource != 0) {
490 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
491 }
492
493 // Cursor-like devices.
494 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
495 device->addMapper(new CursorInputMapper(device));
496 }
497
498 // Touchscreens and touchpad devices.
499 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
500 device->addMapper(new MultiTouchInputMapper(device));
501 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
502 device->addMapper(new SingleTouchInputMapper(device));
503 }
504
505 // Joystick-like devices.
506 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
507 device->addMapper(new JoystickInputMapper(device));
508 }
509
Michael Wright842500e2015-03-13 17:32:02 -0700510 // External stylus-like devices.
511 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
512 device->addMapper(new ExternalStylusInputMapper(device));
513 }
514
Michael Wrightd02c5b62014-02-10 15:10:22 -0800515 return device;
516}
517
518void InputReader::processEventsForDeviceLocked(int32_t deviceId,
519 const RawEvent* rawEvents, size_t count) {
520 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
521 if (deviceIndex < 0) {
522 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
523 return;
524 }
525
526 InputDevice* device = mDevices.valueAt(deviceIndex);
527 if (device->isIgnored()) {
528 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
529 return;
530 }
531
532 device->process(rawEvents, count);
533}
534
535void InputReader::timeoutExpiredLocked(nsecs_t when) {
536 for (size_t i = 0; i < mDevices.size(); i++) {
537 InputDevice* device = mDevices.valueAt(i);
538 if (!device->isIgnored()) {
539 device->timeoutExpired(when);
540 }
541 }
542}
543
544void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
545 // Reset global meta state because it depends on the list of all configured devices.
546 updateGlobalMetaStateLocked();
547
548 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800549 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800550 mQueuedListener->notifyConfigurationChanged(&args);
551}
552
553void InputReader::refreshConfigurationLocked(uint32_t changes) {
554 mPolicy->getReaderConfiguration(&mConfig);
555 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
556
557 if (changes) {
558 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
559 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
560
561 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
562 mEventHub->requestReopenDevices();
563 } else {
564 for (size_t i = 0; i < mDevices.size(); i++) {
565 InputDevice* device = mDevices.valueAt(i);
566 device->configure(now, &mConfig, changes);
567 }
568 }
569 }
570}
571
572void InputReader::updateGlobalMetaStateLocked() {
573 mGlobalMetaState = 0;
574
575 for (size_t i = 0; i < mDevices.size(); i++) {
576 InputDevice* device = mDevices.valueAt(i);
577 mGlobalMetaState |= device->getMetaState();
578 }
579}
580
581int32_t InputReader::getGlobalMetaStateLocked() {
582 return mGlobalMetaState;
583}
584
Michael Wright842500e2015-03-13 17:32:02 -0700585void InputReader::notifyExternalStylusPresenceChanged() {
586 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
587}
588
589void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
590 for (size_t i = 0; i < mDevices.size(); i++) {
591 InputDevice* device = mDevices.valueAt(i);
592 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
593 outDevices.push();
594 device->getDeviceInfo(&outDevices.editTop());
595 }
596 }
597}
598
599void InputReader::dispatchExternalStylusState(const StylusState& state) {
600 for (size_t i = 0; i < mDevices.size(); i++) {
601 InputDevice* device = mDevices.valueAt(i);
602 device->updateExternalStylusState(state);
603 }
604}
605
Michael Wrightd02c5b62014-02-10 15:10:22 -0800606void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
607 mDisableVirtualKeysTimeout = time;
608}
609
610bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
611 InputDevice* device, int32_t keyCode, int32_t scanCode) {
612 if (now < mDisableVirtualKeysTimeout) {
613 ALOGI("Dropping virtual key from device %s because virtual keys are "
614 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100615 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 (mDisableVirtualKeysTimeout - now) * 0.000001,
617 keyCode, scanCode);
618 return true;
619 } else {
620 return false;
621 }
622}
623
624void InputReader::fadePointerLocked() {
625 for (size_t i = 0; i < mDevices.size(); i++) {
626 InputDevice* device = mDevices.valueAt(i);
627 device->fadePointer();
628 }
629}
630
631void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
632 if (when < mNextTimeout) {
633 mNextTimeout = when;
634 mEventHub->wake();
635 }
636}
637
638int32_t InputReader::bumpGenerationLocked() {
639 return ++mGeneration;
640}
641
642void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
643 AutoMutex _l(mLock);
644 getInputDevicesLocked(outInputDevices);
645}
646
647void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
648 outInputDevices.clear();
649
650 size_t numDevices = mDevices.size();
651 for (size_t i = 0; i < numDevices; i++) {
652 InputDevice* device = mDevices.valueAt(i);
653 if (!device->isIgnored()) {
654 outInputDevices.push();
655 device->getDeviceInfo(&outInputDevices.editTop());
656 }
657 }
658}
659
660int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
661 int32_t keyCode) {
662 AutoMutex _l(mLock);
663
664 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
665}
666
667int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
668 int32_t scanCode) {
669 AutoMutex _l(mLock);
670
671 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
672}
673
674int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
675 AutoMutex _l(mLock);
676
677 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
678}
679
680int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
681 GetStateFunc getStateFunc) {
682 int32_t result = AKEY_STATE_UNKNOWN;
683 if (deviceId >= 0) {
684 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
685 if (deviceIndex >= 0) {
686 InputDevice* device = mDevices.valueAt(deviceIndex);
687 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
688 result = (device->*getStateFunc)(sourceMask, code);
689 }
690 }
691 } else {
692 size_t numDevices = mDevices.size();
693 for (size_t i = 0; i < numDevices; i++) {
694 InputDevice* device = mDevices.valueAt(i);
695 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
696 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
697 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
698 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
699 if (currentResult >= AKEY_STATE_DOWN) {
700 return currentResult;
701 } else if (currentResult == AKEY_STATE_UP) {
702 result = currentResult;
703 }
704 }
705 }
706 }
707 return result;
708}
709
Andrii Kulian763a3a42016-03-08 10:46:16 -0800710void InputReader::toggleCapsLockState(int32_t deviceId) {
711 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
712 if (deviceIndex < 0) {
713 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
714 return;
715 }
716
717 InputDevice* device = mDevices.valueAt(deviceIndex);
718 if (device->isIgnored()) {
719 return;
720 }
721
722 device->updateMetaState(AKEYCODE_CAPS_LOCK);
723}
724
Michael Wrightd02c5b62014-02-10 15:10:22 -0800725bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
726 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
727 AutoMutex _l(mLock);
728
729 memset(outFlags, 0, numCodes);
730 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
731}
732
733bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
734 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
735 bool result = false;
736 if (deviceId >= 0) {
737 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
738 if (deviceIndex >= 0) {
739 InputDevice* device = mDevices.valueAt(deviceIndex);
740 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
741 result = device->markSupportedKeyCodes(sourceMask,
742 numCodes, keyCodes, outFlags);
743 }
744 }
745 } else {
746 size_t numDevices = mDevices.size();
747 for (size_t i = 0; i < numDevices; i++) {
748 InputDevice* device = mDevices.valueAt(i);
749 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
750 result |= device->markSupportedKeyCodes(sourceMask,
751 numCodes, keyCodes, outFlags);
752 }
753 }
754 }
755 return result;
756}
757
758void InputReader::requestRefreshConfiguration(uint32_t changes) {
759 AutoMutex _l(mLock);
760
761 if (changes) {
762 bool needWake = !mConfigurationChangesToRefresh;
763 mConfigurationChangesToRefresh |= changes;
764
765 if (needWake) {
766 mEventHub->wake();
767 }
768 }
769}
770
771void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
772 ssize_t repeat, int32_t token) {
773 AutoMutex _l(mLock);
774
775 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
776 if (deviceIndex >= 0) {
777 InputDevice* device = mDevices.valueAt(deviceIndex);
778 device->vibrate(pattern, patternSize, repeat, token);
779 }
780}
781
782void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
783 AutoMutex _l(mLock);
784
785 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
786 if (deviceIndex >= 0) {
787 InputDevice* device = mDevices.valueAt(deviceIndex);
788 device->cancelVibrate(token);
789 }
790}
791
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700792bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
793 AutoMutex _l(mLock);
794
795 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
796 if (deviceIndex >= 0) {
797 InputDevice* device = mDevices.valueAt(deviceIndex);
798 return device->isEnabled();
799 }
800 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
801 return false;
802}
803
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800804void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800805 AutoMutex _l(mLock);
806
807 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800808 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800809
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800810 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800811
812 for (size_t i = 0; i < mDevices.size(); i++) {
813 mDevices.valueAt(i)->dump(dump);
814 }
815
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800816 dump += INDENT "Configuration:\n";
817 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800818 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
819 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800820 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800821 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100822 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800823 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800824 dump += "]\n";
825 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800826 mConfig.virtualKeyQuietTime * 0.000001f);
827
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800828 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800829 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
830 mConfig.pointerVelocityControlParameters.scale,
831 mConfig.pointerVelocityControlParameters.lowThreshold,
832 mConfig.pointerVelocityControlParameters.highThreshold,
833 mConfig.pointerVelocityControlParameters.acceleration);
834
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800835 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800836 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
837 mConfig.wheelVelocityControlParameters.scale,
838 mConfig.wheelVelocityControlParameters.lowThreshold,
839 mConfig.wheelVelocityControlParameters.highThreshold,
840 mConfig.wheelVelocityControlParameters.acceleration);
841
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800842 dump += StringPrintf(INDENT2 "PointerGesture:\n");
843 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800844 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800845 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800846 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800847 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800849 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800850 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800851 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800852 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800853 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800854 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800855 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800856 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800857 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800858 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800859 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800860 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800861 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800862 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800863 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800864 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800865 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800866 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700867
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800868 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700869 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800870}
871
872void InputReader::monitor() {
873 // Acquire and release the lock to ensure that the reader has not deadlocked.
874 mLock.lock();
875 mEventHub->wake();
876 mReaderIsAliveCondition.wait(mLock);
877 mLock.unlock();
878
879 // Check the EventHub
880 mEventHub->monitor();
881}
882
883
884// --- InputReader::ContextImpl ---
885
886InputReader::ContextImpl::ContextImpl(InputReader* reader) :
887 mReader(reader) {
888}
889
890void InputReader::ContextImpl::updateGlobalMetaState() {
891 // lock is already held by the input loop
892 mReader->updateGlobalMetaStateLocked();
893}
894
895int32_t InputReader::ContextImpl::getGlobalMetaState() {
896 // lock is already held by the input loop
897 return mReader->getGlobalMetaStateLocked();
898}
899
900void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
901 // lock is already held by the input loop
902 mReader->disableVirtualKeysUntilLocked(time);
903}
904
905bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
906 InputDevice* device, int32_t keyCode, int32_t scanCode) {
907 // lock is already held by the input loop
908 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
909}
910
911void InputReader::ContextImpl::fadePointer() {
912 // lock is already held by the input loop
913 mReader->fadePointerLocked();
914}
915
916void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
917 // lock is already held by the input loop
918 mReader->requestTimeoutAtTimeLocked(when);
919}
920
921int32_t InputReader::ContextImpl::bumpGeneration() {
922 // lock is already held by the input loop
923 return mReader->bumpGenerationLocked();
924}
925
Michael Wright842500e2015-03-13 17:32:02 -0700926void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
927 // lock is already held by whatever called refreshConfigurationLocked
928 mReader->getExternalStylusDevicesLocked(outDevices);
929}
930
931void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
932 mReader->dispatchExternalStylusState(state);
933}
934
Michael Wrightd02c5b62014-02-10 15:10:22 -0800935InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
936 return mReader->mPolicy.get();
937}
938
939InputListenerInterface* InputReader::ContextImpl::getListener() {
940 return mReader->mQueuedListener.get();
941}
942
943EventHubInterface* InputReader::ContextImpl::getEventHub() {
944 return mReader->mEventHub.get();
945}
946
Prabir Pradhan42611e02018-11-27 14:04:02 -0800947uint32_t InputReader::ContextImpl::getNextSequenceNum() {
948 return (mReader->mNextSequenceNum)++;
949}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800950
Michael Wrightd02c5b62014-02-10 15:10:22 -0800951// --- InputDevice ---
952
953InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
954 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
955 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
956 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700957 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800958}
959
960InputDevice::~InputDevice() {
961 size_t numMappers = mMappers.size();
962 for (size_t i = 0; i < numMappers; i++) {
963 delete mMappers[i];
964 }
965 mMappers.clear();
966}
967
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700968bool InputDevice::isEnabled() {
969 return getEventHub()->isDeviceEnabled(mId);
970}
971
972void InputDevice::setEnabled(bool enabled, nsecs_t when) {
973 if (isEnabled() == enabled) {
974 return;
975 }
976
977 if (enabled) {
978 getEventHub()->enableDevice(mId);
979 reset(when);
980 } else {
981 reset(when);
982 getEventHub()->disableDevice(mId);
983 }
984 // Must change generation to flag this device as changed
985 bumpGeneration();
986}
987
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800988void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700990 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800991
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100993 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800994 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
995 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -0700996 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
997 if (mAssociatedDisplayPort) {
998 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
999 } else {
1000 dump += "<none>\n";
1001 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001002 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1003 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1004 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001005
1006 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1007 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001008 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001009 for (size_t i = 0; i < ranges.size(); i++) {
1010 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1011 const char* label = getAxisLabel(range.axis);
1012 char name[32];
1013 if (label) {
1014 strncpy(name, label, sizeof(name));
1015 name[sizeof(name) - 1] = '\0';
1016 } else {
1017 snprintf(name, sizeof(name), "%d", range.axis);
1018 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001019 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001020 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1021 name, range.source, range.min, range.max, range.flat, range.fuzz,
1022 range.resolution);
1023 }
1024 }
1025
1026 size_t numMappers = mMappers.size();
1027 for (size_t i = 0; i < numMappers; i++) {
1028 InputMapper* mapper = mMappers[i];
1029 mapper->dump(dump);
1030 }
1031}
1032
1033void InputDevice::addMapper(InputMapper* mapper) {
1034 mMappers.add(mapper);
1035}
1036
1037void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1038 mSources = 0;
1039
1040 if (!isIgnored()) {
1041 if (!changes) { // first time only
1042 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1043 }
1044
1045 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1046 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1047 sp<KeyCharacterMap> keyboardLayout =
1048 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1049 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1050 bumpGeneration();
1051 }
1052 }
1053 }
1054
1055 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1056 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001057 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001058 if (mAlias != alias) {
1059 mAlias = alias;
1060 bumpGeneration();
1061 }
1062 }
1063 }
1064
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001065 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1066 ssize_t index = config->disabledDevices.indexOf(mId);
1067 bool enabled = index < 0;
1068 setEnabled(enabled, when);
1069 }
1070
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001071 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1072 // In most situations, no port will be specified.
1073 mAssociatedDisplayPort = std::nullopt;
1074 // Find the display port that corresponds to the current input port.
1075 const std::string& inputPort = mIdentifier.location;
1076 if (!inputPort.empty()) {
1077 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1078 const auto& displayPort = ports.find(inputPort);
1079 if (displayPort != ports.end()) {
1080 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1081 }
1082 }
1083 }
1084
Michael Wrightd02c5b62014-02-10 15:10:22 -08001085 size_t numMappers = mMappers.size();
1086 for (size_t i = 0; i < numMappers; i++) {
1087 InputMapper* mapper = mMappers[i];
1088 mapper->configure(when, config, changes);
1089 mSources |= mapper->getSources();
1090 }
1091 }
1092}
1093
1094void InputDevice::reset(nsecs_t when) {
1095 size_t numMappers = mMappers.size();
1096 for (size_t i = 0; i < numMappers; i++) {
1097 InputMapper* mapper = mMappers[i];
1098 mapper->reset(when);
1099 }
1100
1101 mContext->updateGlobalMetaState();
1102
1103 notifyReset(when);
1104}
1105
1106void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1107 // Process all of the events in order for each mapper.
1108 // We cannot simply ask each mapper to process them in bulk because mappers may
1109 // have side-effects that must be interleaved. For example, joystick movement events and
1110 // gamepad button presses are handled by different mappers but they should be dispatched
1111 // in the order received.
1112 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001113 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001115 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001116 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1117 rawEvent->when);
1118#endif
1119
1120 if (mDropUntilNextSync) {
1121 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1122 mDropUntilNextSync = false;
1123#if DEBUG_RAW_EVENTS
1124 ALOGD("Recovered from input event buffer overrun.");
1125#endif
1126 } else {
1127#if DEBUG_RAW_EVENTS
1128 ALOGD("Dropped input event while waiting for next input sync.");
1129#endif
1130 }
1131 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001132 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001133 mDropUntilNextSync = true;
1134 reset(rawEvent->when);
1135 } else {
1136 for (size_t i = 0; i < numMappers; i++) {
1137 InputMapper* mapper = mMappers[i];
1138 mapper->process(rawEvent);
1139 }
1140 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001141 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 }
1143}
1144
1145void InputDevice::timeoutExpired(nsecs_t when) {
1146 size_t numMappers = mMappers.size();
1147 for (size_t i = 0; i < numMappers; i++) {
1148 InputMapper* mapper = mMappers[i];
1149 mapper->timeoutExpired(when);
1150 }
1151}
1152
Michael Wright842500e2015-03-13 17:32:02 -07001153void InputDevice::updateExternalStylusState(const StylusState& state) {
1154 size_t numMappers = mMappers.size();
1155 for (size_t i = 0; i < numMappers; i++) {
1156 InputMapper* mapper = mMappers[i];
1157 mapper->updateExternalStylusState(state);
1158 }
1159}
1160
Michael Wrightd02c5b62014-02-10 15:10:22 -08001161void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1162 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001163 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001164 size_t numMappers = mMappers.size();
1165 for (size_t i = 0; i < numMappers; i++) {
1166 InputMapper* mapper = mMappers[i];
1167 mapper->populateDeviceInfo(outDeviceInfo);
1168 }
1169}
1170
1171int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1172 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1173}
1174
1175int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1176 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1177}
1178
1179int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1180 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1181}
1182
1183int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1184 int32_t result = AKEY_STATE_UNKNOWN;
1185 size_t numMappers = mMappers.size();
1186 for (size_t i = 0; i < numMappers; i++) {
1187 InputMapper* mapper = mMappers[i];
1188 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1189 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1190 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1191 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1192 if (currentResult >= AKEY_STATE_DOWN) {
1193 return currentResult;
1194 } else if (currentResult == AKEY_STATE_UP) {
1195 result = currentResult;
1196 }
1197 }
1198 }
1199 return result;
1200}
1201
1202bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1203 const int32_t* keyCodes, uint8_t* outFlags) {
1204 bool result = false;
1205 size_t numMappers = mMappers.size();
1206 for (size_t i = 0; i < numMappers; i++) {
1207 InputMapper* mapper = mMappers[i];
1208 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1209 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1210 }
1211 }
1212 return result;
1213}
1214
1215void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1216 int32_t token) {
1217 size_t numMappers = mMappers.size();
1218 for (size_t i = 0; i < numMappers; i++) {
1219 InputMapper* mapper = mMappers[i];
1220 mapper->vibrate(pattern, patternSize, repeat, token);
1221 }
1222}
1223
1224void InputDevice::cancelVibrate(int32_t token) {
1225 size_t numMappers = mMappers.size();
1226 for (size_t i = 0; i < numMappers; i++) {
1227 InputMapper* mapper = mMappers[i];
1228 mapper->cancelVibrate(token);
1229 }
1230}
1231
Jeff Brownc9aa6282015-02-11 19:03:28 -08001232void InputDevice::cancelTouch(nsecs_t when) {
1233 size_t numMappers = mMappers.size();
1234 for (size_t i = 0; i < numMappers; i++) {
1235 InputMapper* mapper = mMappers[i];
1236 mapper->cancelTouch(when);
1237 }
1238}
1239
Michael Wrightd02c5b62014-02-10 15:10:22 -08001240int32_t InputDevice::getMetaState() {
1241 int32_t result = 0;
1242 size_t numMappers = mMappers.size();
1243 for (size_t i = 0; i < numMappers; i++) {
1244 InputMapper* mapper = mMappers[i];
1245 result |= mapper->getMetaState();
1246 }
1247 return result;
1248}
1249
Andrii Kulian763a3a42016-03-08 10:46:16 -08001250void InputDevice::updateMetaState(int32_t keyCode) {
1251 size_t numMappers = mMappers.size();
1252 for (size_t i = 0; i < numMappers; i++) {
1253 mMappers[i]->updateMetaState(keyCode);
1254 }
1255}
1256
Michael Wrightd02c5b62014-02-10 15:10:22 -08001257void InputDevice::fadePointer() {
1258 size_t numMappers = mMappers.size();
1259 for (size_t i = 0; i < numMappers; i++) {
1260 InputMapper* mapper = mMappers[i];
1261 mapper->fadePointer();
1262 }
1263}
1264
1265void InputDevice::bumpGeneration() {
1266 mGeneration = mContext->bumpGeneration();
1267}
1268
1269void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001270 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001271 mContext->getListener()->notifyDeviceReset(&args);
1272}
1273
1274
1275// --- CursorButtonAccumulator ---
1276
1277CursorButtonAccumulator::CursorButtonAccumulator() {
1278 clearButtons();
1279}
1280
1281void CursorButtonAccumulator::reset(InputDevice* device) {
1282 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1283 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1284 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1285 mBtnBack = device->isKeyPressed(BTN_BACK);
1286 mBtnSide = device->isKeyPressed(BTN_SIDE);
1287 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1288 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1289 mBtnTask = device->isKeyPressed(BTN_TASK);
1290}
1291
1292void CursorButtonAccumulator::clearButtons() {
1293 mBtnLeft = 0;
1294 mBtnRight = 0;
1295 mBtnMiddle = 0;
1296 mBtnBack = 0;
1297 mBtnSide = 0;
1298 mBtnForward = 0;
1299 mBtnExtra = 0;
1300 mBtnTask = 0;
1301}
1302
1303void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1304 if (rawEvent->type == EV_KEY) {
1305 switch (rawEvent->code) {
1306 case BTN_LEFT:
1307 mBtnLeft = rawEvent->value;
1308 break;
1309 case BTN_RIGHT:
1310 mBtnRight = rawEvent->value;
1311 break;
1312 case BTN_MIDDLE:
1313 mBtnMiddle = rawEvent->value;
1314 break;
1315 case BTN_BACK:
1316 mBtnBack = rawEvent->value;
1317 break;
1318 case BTN_SIDE:
1319 mBtnSide = rawEvent->value;
1320 break;
1321 case BTN_FORWARD:
1322 mBtnForward = rawEvent->value;
1323 break;
1324 case BTN_EXTRA:
1325 mBtnExtra = rawEvent->value;
1326 break;
1327 case BTN_TASK:
1328 mBtnTask = rawEvent->value;
1329 break;
1330 }
1331 }
1332}
1333
1334uint32_t CursorButtonAccumulator::getButtonState() const {
1335 uint32_t result = 0;
1336 if (mBtnLeft) {
1337 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1338 }
1339 if (mBtnRight) {
1340 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1341 }
1342 if (mBtnMiddle) {
1343 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1344 }
1345 if (mBtnBack || mBtnSide) {
1346 result |= AMOTION_EVENT_BUTTON_BACK;
1347 }
1348 if (mBtnForward || mBtnExtra) {
1349 result |= AMOTION_EVENT_BUTTON_FORWARD;
1350 }
1351 return result;
1352}
1353
1354
1355// --- CursorMotionAccumulator ---
1356
1357CursorMotionAccumulator::CursorMotionAccumulator() {
1358 clearRelativeAxes();
1359}
1360
1361void CursorMotionAccumulator::reset(InputDevice* device) {
1362 clearRelativeAxes();
1363}
1364
1365void CursorMotionAccumulator::clearRelativeAxes() {
1366 mRelX = 0;
1367 mRelY = 0;
1368}
1369
1370void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1371 if (rawEvent->type == EV_REL) {
1372 switch (rawEvent->code) {
1373 case REL_X:
1374 mRelX = rawEvent->value;
1375 break;
1376 case REL_Y:
1377 mRelY = rawEvent->value;
1378 break;
1379 }
1380 }
1381}
1382
1383void CursorMotionAccumulator::finishSync() {
1384 clearRelativeAxes();
1385}
1386
1387
1388// --- CursorScrollAccumulator ---
1389
1390CursorScrollAccumulator::CursorScrollAccumulator() :
1391 mHaveRelWheel(false), mHaveRelHWheel(false) {
1392 clearRelativeAxes();
1393}
1394
1395void CursorScrollAccumulator::configure(InputDevice* device) {
1396 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1397 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1398}
1399
1400void CursorScrollAccumulator::reset(InputDevice* device) {
1401 clearRelativeAxes();
1402}
1403
1404void CursorScrollAccumulator::clearRelativeAxes() {
1405 mRelWheel = 0;
1406 mRelHWheel = 0;
1407}
1408
1409void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1410 if (rawEvent->type == EV_REL) {
1411 switch (rawEvent->code) {
1412 case REL_WHEEL:
1413 mRelWheel = rawEvent->value;
1414 break;
1415 case REL_HWHEEL:
1416 mRelHWheel = rawEvent->value;
1417 break;
1418 }
1419 }
1420}
1421
1422void CursorScrollAccumulator::finishSync() {
1423 clearRelativeAxes();
1424}
1425
1426
1427// --- TouchButtonAccumulator ---
1428
1429TouchButtonAccumulator::TouchButtonAccumulator() :
1430 mHaveBtnTouch(false), mHaveStylus(false) {
1431 clearButtons();
1432}
1433
1434void TouchButtonAccumulator::configure(InputDevice* device) {
1435 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1436 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1437 || device->hasKey(BTN_TOOL_RUBBER)
1438 || device->hasKey(BTN_TOOL_BRUSH)
1439 || device->hasKey(BTN_TOOL_PENCIL)
1440 || device->hasKey(BTN_TOOL_AIRBRUSH);
1441}
1442
1443void TouchButtonAccumulator::reset(InputDevice* device) {
1444 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1445 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001446 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1447 mBtnStylus2 =
1448 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001449 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1450 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1451 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1452 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1453 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1454 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1455 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1456 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1457 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1458 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1459 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1460}
1461
1462void TouchButtonAccumulator::clearButtons() {
1463 mBtnTouch = 0;
1464 mBtnStylus = 0;
1465 mBtnStylus2 = 0;
1466 mBtnToolFinger = 0;
1467 mBtnToolPen = 0;
1468 mBtnToolRubber = 0;
1469 mBtnToolBrush = 0;
1470 mBtnToolPencil = 0;
1471 mBtnToolAirbrush = 0;
1472 mBtnToolMouse = 0;
1473 mBtnToolLens = 0;
1474 mBtnToolDoubleTap = 0;
1475 mBtnToolTripleTap = 0;
1476 mBtnToolQuadTap = 0;
1477}
1478
1479void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1480 if (rawEvent->type == EV_KEY) {
1481 switch (rawEvent->code) {
1482 case BTN_TOUCH:
1483 mBtnTouch = rawEvent->value;
1484 break;
1485 case BTN_STYLUS:
1486 mBtnStylus = rawEvent->value;
1487 break;
1488 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001489 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001490 mBtnStylus2 = rawEvent->value;
1491 break;
1492 case BTN_TOOL_FINGER:
1493 mBtnToolFinger = rawEvent->value;
1494 break;
1495 case BTN_TOOL_PEN:
1496 mBtnToolPen = rawEvent->value;
1497 break;
1498 case BTN_TOOL_RUBBER:
1499 mBtnToolRubber = rawEvent->value;
1500 break;
1501 case BTN_TOOL_BRUSH:
1502 mBtnToolBrush = rawEvent->value;
1503 break;
1504 case BTN_TOOL_PENCIL:
1505 mBtnToolPencil = rawEvent->value;
1506 break;
1507 case BTN_TOOL_AIRBRUSH:
1508 mBtnToolAirbrush = rawEvent->value;
1509 break;
1510 case BTN_TOOL_MOUSE:
1511 mBtnToolMouse = rawEvent->value;
1512 break;
1513 case BTN_TOOL_LENS:
1514 mBtnToolLens = rawEvent->value;
1515 break;
1516 case BTN_TOOL_DOUBLETAP:
1517 mBtnToolDoubleTap = rawEvent->value;
1518 break;
1519 case BTN_TOOL_TRIPLETAP:
1520 mBtnToolTripleTap = rawEvent->value;
1521 break;
1522 case BTN_TOOL_QUADTAP:
1523 mBtnToolQuadTap = rawEvent->value;
1524 break;
1525 }
1526 }
1527}
1528
1529uint32_t TouchButtonAccumulator::getButtonState() const {
1530 uint32_t result = 0;
1531 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001532 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001533 }
1534 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001535 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001536 }
1537 return result;
1538}
1539
1540int32_t TouchButtonAccumulator::getToolType() const {
1541 if (mBtnToolMouse || mBtnToolLens) {
1542 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1543 }
1544 if (mBtnToolRubber) {
1545 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1546 }
1547 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1548 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1549 }
1550 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1551 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1552 }
1553 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1554}
1555
1556bool TouchButtonAccumulator::isToolActive() const {
1557 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1558 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1559 || mBtnToolMouse || mBtnToolLens
1560 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1561}
1562
1563bool TouchButtonAccumulator::isHovering() const {
1564 return mHaveBtnTouch && !mBtnTouch;
1565}
1566
1567bool TouchButtonAccumulator::hasStylus() const {
1568 return mHaveStylus;
1569}
1570
1571
1572// --- RawPointerAxes ---
1573
1574RawPointerAxes::RawPointerAxes() {
1575 clear();
1576}
1577
1578void RawPointerAxes::clear() {
1579 x.clear();
1580 y.clear();
1581 pressure.clear();
1582 touchMajor.clear();
1583 touchMinor.clear();
1584 toolMajor.clear();
1585 toolMinor.clear();
1586 orientation.clear();
1587 distance.clear();
1588 tiltX.clear();
1589 tiltY.clear();
1590 trackingId.clear();
1591 slot.clear();
1592}
1593
1594
1595// --- RawPointerData ---
1596
1597RawPointerData::RawPointerData() {
1598 clear();
1599}
1600
1601void RawPointerData::clear() {
1602 pointerCount = 0;
1603 clearIdBits();
1604}
1605
1606void RawPointerData::copyFrom(const RawPointerData& other) {
1607 pointerCount = other.pointerCount;
1608 hoveringIdBits = other.hoveringIdBits;
1609 touchingIdBits = other.touchingIdBits;
1610
1611 for (uint32_t i = 0; i < pointerCount; i++) {
1612 pointers[i] = other.pointers[i];
1613
1614 int id = pointers[i].id;
1615 idToIndex[id] = other.idToIndex[id];
1616 }
1617}
1618
1619void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1620 float x = 0, y = 0;
1621 uint32_t count = touchingIdBits.count();
1622 if (count) {
1623 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1624 uint32_t id = idBits.clearFirstMarkedBit();
1625 const Pointer& pointer = pointerForId(id);
1626 x += pointer.x;
1627 y += pointer.y;
1628 }
1629 x /= count;
1630 y /= count;
1631 }
1632 *outX = x;
1633 *outY = y;
1634}
1635
1636
1637// --- CookedPointerData ---
1638
1639CookedPointerData::CookedPointerData() {
1640 clear();
1641}
1642
1643void CookedPointerData::clear() {
1644 pointerCount = 0;
1645 hoveringIdBits.clear();
1646 touchingIdBits.clear();
1647}
1648
1649void CookedPointerData::copyFrom(const CookedPointerData& other) {
1650 pointerCount = other.pointerCount;
1651 hoveringIdBits = other.hoveringIdBits;
1652 touchingIdBits = other.touchingIdBits;
1653
1654 for (uint32_t i = 0; i < pointerCount; i++) {
1655 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1656 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1657
1658 int id = pointerProperties[i].id;
1659 idToIndex[id] = other.idToIndex[id];
1660 }
1661}
1662
1663
1664// --- SingleTouchMotionAccumulator ---
1665
1666SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1667 clearAbsoluteAxes();
1668}
1669
1670void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1671 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1672 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1673 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1674 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1675 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1676 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1677 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1678}
1679
1680void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1681 mAbsX = 0;
1682 mAbsY = 0;
1683 mAbsPressure = 0;
1684 mAbsToolWidth = 0;
1685 mAbsDistance = 0;
1686 mAbsTiltX = 0;
1687 mAbsTiltY = 0;
1688}
1689
1690void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1691 if (rawEvent->type == EV_ABS) {
1692 switch (rawEvent->code) {
1693 case ABS_X:
1694 mAbsX = rawEvent->value;
1695 break;
1696 case ABS_Y:
1697 mAbsY = rawEvent->value;
1698 break;
1699 case ABS_PRESSURE:
1700 mAbsPressure = rawEvent->value;
1701 break;
1702 case ABS_TOOL_WIDTH:
1703 mAbsToolWidth = rawEvent->value;
1704 break;
1705 case ABS_DISTANCE:
1706 mAbsDistance = rawEvent->value;
1707 break;
1708 case ABS_TILT_X:
1709 mAbsTiltX = rawEvent->value;
1710 break;
1711 case ABS_TILT_Y:
1712 mAbsTiltY = rawEvent->value;
1713 break;
1714 }
1715 }
1716}
1717
1718
1719// --- MultiTouchMotionAccumulator ---
1720
1721MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001722 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001723 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001724}
1725
1726MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1727 delete[] mSlots;
1728}
1729
1730void MultiTouchMotionAccumulator::configure(InputDevice* device,
1731 size_t slotCount, bool usingSlotsProtocol) {
1732 mSlotCount = slotCount;
1733 mUsingSlotsProtocol = usingSlotsProtocol;
1734 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1735
1736 delete[] mSlots;
1737 mSlots = new Slot[slotCount];
1738}
1739
1740void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1741 // Unfortunately there is no way to read the initial contents of the slots.
1742 // So when we reset the accumulator, we must assume they are all zeroes.
1743 if (mUsingSlotsProtocol) {
1744 // Query the driver for the current slot index and use it as the initial slot
1745 // before we start reading events from the device. It is possible that the
1746 // current slot index will not be the same as it was when the first event was
1747 // written into the evdev buffer, which means the input mapper could start
1748 // out of sync with the initial state of the events in the evdev buffer.
1749 // In the extremely unlikely case that this happens, the data from
1750 // two slots will be confused until the next ABS_MT_SLOT event is received.
1751 // This can cause the touch point to "jump", but at least there will be
1752 // no stuck touches.
1753 int32_t initialSlot;
1754 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1755 ABS_MT_SLOT, &initialSlot);
1756 if (status) {
1757 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1758 initialSlot = -1;
1759 }
1760 clearSlots(initialSlot);
1761 } else {
1762 clearSlots(-1);
1763 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001764 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765}
1766
1767void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1768 if (mSlots) {
1769 for (size_t i = 0; i < mSlotCount; i++) {
1770 mSlots[i].clear();
1771 }
1772 }
1773 mCurrentSlot = initialSlot;
1774}
1775
1776void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1777 if (rawEvent->type == EV_ABS) {
1778 bool newSlot = false;
1779 if (mUsingSlotsProtocol) {
1780 if (rawEvent->code == ABS_MT_SLOT) {
1781 mCurrentSlot = rawEvent->value;
1782 newSlot = true;
1783 }
1784 } else if (mCurrentSlot < 0) {
1785 mCurrentSlot = 0;
1786 }
1787
1788 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1789#if DEBUG_POINTERS
1790 if (newSlot) {
1791 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001792 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001793 mCurrentSlot, mSlotCount - 1);
1794 }
1795#endif
1796 } else {
1797 Slot* slot = &mSlots[mCurrentSlot];
1798
1799 switch (rawEvent->code) {
1800 case ABS_MT_POSITION_X:
1801 slot->mInUse = true;
1802 slot->mAbsMTPositionX = rawEvent->value;
1803 break;
1804 case ABS_MT_POSITION_Y:
1805 slot->mInUse = true;
1806 slot->mAbsMTPositionY = rawEvent->value;
1807 break;
1808 case ABS_MT_TOUCH_MAJOR:
1809 slot->mInUse = true;
1810 slot->mAbsMTTouchMajor = rawEvent->value;
1811 break;
1812 case ABS_MT_TOUCH_MINOR:
1813 slot->mInUse = true;
1814 slot->mAbsMTTouchMinor = rawEvent->value;
1815 slot->mHaveAbsMTTouchMinor = true;
1816 break;
1817 case ABS_MT_WIDTH_MAJOR:
1818 slot->mInUse = true;
1819 slot->mAbsMTWidthMajor = rawEvent->value;
1820 break;
1821 case ABS_MT_WIDTH_MINOR:
1822 slot->mInUse = true;
1823 slot->mAbsMTWidthMinor = rawEvent->value;
1824 slot->mHaveAbsMTWidthMinor = true;
1825 break;
1826 case ABS_MT_ORIENTATION:
1827 slot->mInUse = true;
1828 slot->mAbsMTOrientation = rawEvent->value;
1829 break;
1830 case ABS_MT_TRACKING_ID:
1831 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1832 // The slot is no longer in use but it retains its previous contents,
1833 // which may be reused for subsequent touches.
1834 slot->mInUse = false;
1835 } else {
1836 slot->mInUse = true;
1837 slot->mAbsMTTrackingId = rawEvent->value;
1838 }
1839 break;
1840 case ABS_MT_PRESSURE:
1841 slot->mInUse = true;
1842 slot->mAbsMTPressure = rawEvent->value;
1843 break;
1844 case ABS_MT_DISTANCE:
1845 slot->mInUse = true;
1846 slot->mAbsMTDistance = rawEvent->value;
1847 break;
1848 case ABS_MT_TOOL_TYPE:
1849 slot->mInUse = true;
1850 slot->mAbsMTToolType = rawEvent->value;
1851 slot->mHaveAbsMTToolType = true;
1852 break;
1853 }
1854 }
1855 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1856 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1857 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001858 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1859 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001860 }
1861}
1862
1863void MultiTouchMotionAccumulator::finishSync() {
1864 if (!mUsingSlotsProtocol) {
1865 clearSlots(-1);
1866 }
1867}
1868
1869bool MultiTouchMotionAccumulator::hasStylus() const {
1870 return mHaveStylus;
1871}
1872
1873
1874// --- MultiTouchMotionAccumulator::Slot ---
1875
1876MultiTouchMotionAccumulator::Slot::Slot() {
1877 clear();
1878}
1879
1880void MultiTouchMotionAccumulator::Slot::clear() {
1881 mInUse = false;
1882 mHaveAbsMTTouchMinor = false;
1883 mHaveAbsMTWidthMinor = false;
1884 mHaveAbsMTToolType = false;
1885 mAbsMTPositionX = 0;
1886 mAbsMTPositionY = 0;
1887 mAbsMTTouchMajor = 0;
1888 mAbsMTTouchMinor = 0;
1889 mAbsMTWidthMajor = 0;
1890 mAbsMTWidthMinor = 0;
1891 mAbsMTOrientation = 0;
1892 mAbsMTTrackingId = -1;
1893 mAbsMTPressure = 0;
1894 mAbsMTDistance = 0;
1895 mAbsMTToolType = 0;
1896}
1897
1898int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1899 if (mHaveAbsMTToolType) {
1900 switch (mAbsMTToolType) {
1901 case MT_TOOL_FINGER:
1902 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1903 case MT_TOOL_PEN:
1904 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1905 }
1906 }
1907 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1908}
1909
1910
1911// --- InputMapper ---
1912
1913InputMapper::InputMapper(InputDevice* device) :
1914 mDevice(device), mContext(device->getContext()) {
1915}
1916
1917InputMapper::~InputMapper() {
1918}
1919
1920void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1921 info->addSource(getSources());
1922}
1923
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001924void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001925}
1926
1927void InputMapper::configure(nsecs_t when,
1928 const InputReaderConfiguration* config, uint32_t changes) {
1929}
1930
1931void InputMapper::reset(nsecs_t when) {
1932}
1933
1934void InputMapper::timeoutExpired(nsecs_t when) {
1935}
1936
1937int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1938 return AKEY_STATE_UNKNOWN;
1939}
1940
1941int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1942 return AKEY_STATE_UNKNOWN;
1943}
1944
1945int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1946 return AKEY_STATE_UNKNOWN;
1947}
1948
1949bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1950 const int32_t* keyCodes, uint8_t* outFlags) {
1951 return false;
1952}
1953
1954void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1955 int32_t token) {
1956}
1957
1958void InputMapper::cancelVibrate(int32_t token) {
1959}
1960
Jeff Brownc9aa6282015-02-11 19:03:28 -08001961void InputMapper::cancelTouch(nsecs_t when) {
1962}
1963
Michael Wrightd02c5b62014-02-10 15:10:22 -08001964int32_t InputMapper::getMetaState() {
1965 return 0;
1966}
1967
Andrii Kulian763a3a42016-03-08 10:46:16 -08001968void InputMapper::updateMetaState(int32_t keyCode) {
1969}
1970
Michael Wright842500e2015-03-13 17:32:02 -07001971void InputMapper::updateExternalStylusState(const StylusState& state) {
1972
1973}
1974
Michael Wrightd02c5b62014-02-10 15:10:22 -08001975void InputMapper::fadePointer() {
1976}
1977
1978status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1979 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1980}
1981
1982void InputMapper::bumpGeneration() {
1983 mDevice->bumpGeneration();
1984}
1985
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001986void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 const RawAbsoluteAxisInfo& axis, const char* name) {
1988 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001989 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001990 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1991 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001992 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001993 }
1994}
1995
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001996void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1997 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1998 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
1999 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2000 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002001}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002002
2003// --- SwitchInputMapper ---
2004
2005SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002006 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002007}
2008
2009SwitchInputMapper::~SwitchInputMapper() {
2010}
2011
2012uint32_t SwitchInputMapper::getSources() {
2013 return AINPUT_SOURCE_SWITCH;
2014}
2015
2016void SwitchInputMapper::process(const RawEvent* rawEvent) {
2017 switch (rawEvent->type) {
2018 case EV_SW:
2019 processSwitch(rawEvent->code, rawEvent->value);
2020 break;
2021
2022 case EV_SYN:
2023 if (rawEvent->code == SYN_REPORT) {
2024 sync(rawEvent->when);
2025 }
2026 }
2027}
2028
2029void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2030 if (switchCode >= 0 && switchCode < 32) {
2031 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002032 mSwitchValues |= 1 << switchCode;
2033 } else {
2034 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002035 }
2036 mUpdatedSwitchMask |= 1 << switchCode;
2037 }
2038}
2039
2040void SwitchInputMapper::sync(nsecs_t when) {
2041 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002042 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002043 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
2044 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002045 getListener()->notifySwitch(&args);
2046
Michael Wrightd02c5b62014-02-10 15:10:22 -08002047 mUpdatedSwitchMask = 0;
2048 }
2049}
2050
2051int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2052 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2053}
2054
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002055void SwitchInputMapper::dump(std::string& dump) {
2056 dump += INDENT2 "Switch Input Mapper:\n";
2057 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002058}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002059
2060// --- VibratorInputMapper ---
2061
2062VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2063 InputMapper(device), mVibrating(false) {
2064}
2065
2066VibratorInputMapper::~VibratorInputMapper() {
2067}
2068
2069uint32_t VibratorInputMapper::getSources() {
2070 return 0;
2071}
2072
2073void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2074 InputMapper::populateDeviceInfo(info);
2075
2076 info->setVibrator(true);
2077}
2078
2079void VibratorInputMapper::process(const RawEvent* rawEvent) {
2080 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2081}
2082
2083void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2084 int32_t token) {
2085#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002086 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 for (size_t i = 0; i < patternSize; i++) {
2088 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002089 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002090 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002091 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002093 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002094 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002095#endif
2096
2097 mVibrating = true;
2098 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2099 mPatternSize = patternSize;
2100 mRepeat = repeat;
2101 mToken = token;
2102 mIndex = -1;
2103
2104 nextStep();
2105}
2106
2107void VibratorInputMapper::cancelVibrate(int32_t token) {
2108#if DEBUG_VIBRATOR
2109 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2110#endif
2111
2112 if (mVibrating && mToken == token) {
2113 stopVibrating();
2114 }
2115}
2116
2117void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2118 if (mVibrating) {
2119 if (when >= mNextStepTime) {
2120 nextStep();
2121 } else {
2122 getContext()->requestTimeoutAtTime(mNextStepTime);
2123 }
2124 }
2125}
2126
2127void VibratorInputMapper::nextStep() {
2128 mIndex += 1;
2129 if (size_t(mIndex) >= mPatternSize) {
2130 if (mRepeat < 0) {
2131 // We are done.
2132 stopVibrating();
2133 return;
2134 }
2135 mIndex = mRepeat;
2136 }
2137
2138 bool vibratorOn = mIndex & 1;
2139 nsecs_t duration = mPattern[mIndex];
2140 if (vibratorOn) {
2141#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002142 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002143#endif
2144 getEventHub()->vibrate(getDeviceId(), duration);
2145 } else {
2146#if DEBUG_VIBRATOR
2147 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2148#endif
2149 getEventHub()->cancelVibrate(getDeviceId());
2150 }
2151 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2152 mNextStepTime = now + duration;
2153 getContext()->requestTimeoutAtTime(mNextStepTime);
2154#if DEBUG_VIBRATOR
2155 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2156#endif
2157}
2158
2159void VibratorInputMapper::stopVibrating() {
2160 mVibrating = false;
2161#if DEBUG_VIBRATOR
2162 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2163#endif
2164 getEventHub()->cancelVibrate(getDeviceId());
2165}
2166
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002167void VibratorInputMapper::dump(std::string& dump) {
2168 dump += INDENT2 "Vibrator Input Mapper:\n";
2169 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002170}
2171
2172
2173// --- KeyboardInputMapper ---
2174
2175KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2176 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002177 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178}
2179
2180KeyboardInputMapper::~KeyboardInputMapper() {
2181}
2182
2183uint32_t KeyboardInputMapper::getSources() {
2184 return mSource;
2185}
2186
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002187int32_t KeyboardInputMapper::getOrientation() {
2188 if (mViewport) {
2189 return mViewport->orientation;
2190 }
2191 return DISPLAY_ORIENTATION_0;
2192}
2193
2194int32_t KeyboardInputMapper::getDisplayId() {
2195 if (mViewport) {
2196 return mViewport->displayId;
2197 }
2198 return ADISPLAY_ID_NONE;
2199}
2200
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2202 InputMapper::populateDeviceInfo(info);
2203
2204 info->setKeyboardType(mKeyboardType);
2205 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2206}
2207
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002208void KeyboardInputMapper::dump(std::string& dump) {
2209 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002210 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002211 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002212 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002213 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2214 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2215 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002216}
2217
Michael Wrightd02c5b62014-02-10 15:10:22 -08002218void KeyboardInputMapper::configure(nsecs_t when,
2219 const InputReaderConfiguration* config, uint32_t changes) {
2220 InputMapper::configure(when, config, changes);
2221
2222 if (!changes) { // first time only
2223 // Configure basic parameters.
2224 configureParameters();
2225 }
2226
2227 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002228 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002229 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002230 }
2231 }
2232}
2233
Ivan Podogovb9afef32017-02-13 15:34:32 +00002234static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2235 int32_t mapped = 0;
2236 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2237 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2238 if (stemKeyRotationMap[i][0] == keyCode) {
2239 stemKeyRotationMap[i][1] = mapped;
2240 return;
2241 }
2242 }
2243 }
2244}
2245
Michael Wrightd02c5b62014-02-10 15:10:22 -08002246void KeyboardInputMapper::configureParameters() {
2247 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002248 const PropertyMap& config = getDevice()->getConfiguration();
2249 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002250 mParameters.orientationAware);
2251
Michael Wrightd02c5b62014-02-10 15:10:22 -08002252 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002253 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2254 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2255 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2256 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002258
2259 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002260 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002261 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002262}
2263
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002264void KeyboardInputMapper::dumpParameters(std::string& dump) {
2265 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002266 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002268 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002269 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002270}
2271
2272void KeyboardInputMapper::reset(nsecs_t when) {
2273 mMetaState = AMETA_NONE;
2274 mDownTime = 0;
2275 mKeyDowns.clear();
2276 mCurrentHidUsage = 0;
2277
2278 resetLedState();
2279
2280 InputMapper::reset(when);
2281}
2282
2283void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2284 switch (rawEvent->type) {
2285 case EV_KEY: {
2286 int32_t scanCode = rawEvent->code;
2287 int32_t usageCode = mCurrentHidUsage;
2288 mCurrentHidUsage = 0;
2289
2290 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002291 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002292 }
2293 break;
2294 }
2295 case EV_MSC: {
2296 if (rawEvent->code == MSC_SCAN) {
2297 mCurrentHidUsage = rawEvent->value;
2298 }
2299 break;
2300 }
2301 case EV_SYN: {
2302 if (rawEvent->code == SYN_REPORT) {
2303 mCurrentHidUsage = 0;
2304 }
2305 }
2306 }
2307}
2308
2309bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2310 return scanCode < BTN_MOUSE
2311 || scanCode >= KEY_OK
2312 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2313 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2314}
2315
Michael Wright58ba9882017-07-26 16:19:11 +01002316bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2317 switch (keyCode) {
2318 case AKEYCODE_MEDIA_PLAY:
2319 case AKEYCODE_MEDIA_PAUSE:
2320 case AKEYCODE_MEDIA_PLAY_PAUSE:
2321 case AKEYCODE_MUTE:
2322 case AKEYCODE_HEADSETHOOK:
2323 case AKEYCODE_MEDIA_STOP:
2324 case AKEYCODE_MEDIA_NEXT:
2325 case AKEYCODE_MEDIA_PREVIOUS:
2326 case AKEYCODE_MEDIA_REWIND:
2327 case AKEYCODE_MEDIA_RECORD:
2328 case AKEYCODE_MEDIA_FAST_FORWARD:
2329 case AKEYCODE_MEDIA_SKIP_FORWARD:
2330 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2331 case AKEYCODE_MEDIA_STEP_FORWARD:
2332 case AKEYCODE_MEDIA_STEP_BACKWARD:
2333 case AKEYCODE_MEDIA_AUDIO_TRACK:
2334 case AKEYCODE_VOLUME_UP:
2335 case AKEYCODE_VOLUME_DOWN:
2336 case AKEYCODE_VOLUME_MUTE:
2337 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2338 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2339 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2340 return true;
2341 }
2342 return false;
2343}
2344
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002345void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2346 int32_t usageCode) {
2347 int32_t keyCode;
2348 int32_t keyMetaState;
2349 uint32_t policyFlags;
2350
2351 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2352 &keyCode, &keyMetaState, &policyFlags)) {
2353 keyCode = AKEYCODE_UNKNOWN;
2354 keyMetaState = mMetaState;
2355 policyFlags = 0;
2356 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002357
2358 if (down) {
2359 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002360 if (mParameters.orientationAware) {
2361 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002362 }
2363
2364 // Add key down.
2365 ssize_t keyDownIndex = findKeyDown(scanCode);
2366 if (keyDownIndex >= 0) {
2367 // key repeat, be sure to use same keycode as before in case of rotation
2368 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2369 } else {
2370 // key down
2371 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2372 && mContext->shouldDropVirtualKey(when,
2373 getDevice(), keyCode, scanCode)) {
2374 return;
2375 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002376 if (policyFlags & POLICY_FLAG_GESTURE) {
2377 mDevice->cancelTouch(when);
2378 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002379
2380 mKeyDowns.push();
2381 KeyDown& keyDown = mKeyDowns.editTop();
2382 keyDown.keyCode = keyCode;
2383 keyDown.scanCode = scanCode;
2384 }
2385
2386 mDownTime = when;
2387 } else {
2388 // Remove key down.
2389 ssize_t keyDownIndex = findKeyDown(scanCode);
2390 if (keyDownIndex >= 0) {
2391 // key up, be sure to use same keycode as before in case of rotation
2392 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2393 mKeyDowns.removeAt(size_t(keyDownIndex));
2394 } else {
2395 // key was not actually down
2396 ALOGI("Dropping key up from device %s because the key was not down. "
2397 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002398 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002399 return;
2400 }
2401 }
2402
Andrii Kulian763a3a42016-03-08 10:46:16 -08002403 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002404 // If global meta state changed send it along with the key.
2405 // If it has not changed then we'll use what keymap gave us,
2406 // since key replacement logic might temporarily reset a few
2407 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002408 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 }
2410
2411 nsecs_t downTime = mDownTime;
2412
2413 // Key down on external an keyboard should wake the device.
2414 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2415 // For internal keyboards, the key layout file should specify the policy flags for
2416 // each wake key individually.
2417 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002418 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002419 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002420 }
2421
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002422 if (mParameters.handlesKeyRepeat) {
2423 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2424 }
2425
Prabir Pradhan42611e02018-11-27 14:04:02 -08002426 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2427 getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002428 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002429 getListener()->notifyKey(&args);
2430}
2431
2432ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2433 size_t n = mKeyDowns.size();
2434 for (size_t i = 0; i < n; i++) {
2435 if (mKeyDowns[i].scanCode == scanCode) {
2436 return i;
2437 }
2438 }
2439 return -1;
2440}
2441
2442int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2443 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2444}
2445
2446int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2447 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2448}
2449
2450bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2451 const int32_t* keyCodes, uint8_t* outFlags) {
2452 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2453}
2454
2455int32_t KeyboardInputMapper::getMetaState() {
2456 return mMetaState;
2457}
2458
Andrii Kulian763a3a42016-03-08 10:46:16 -08002459void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2460 updateMetaStateIfNeeded(keyCode, false);
2461}
2462
2463bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2464 int32_t oldMetaState = mMetaState;
2465 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2466 bool metaStateChanged = oldMetaState != newMetaState;
2467 if (metaStateChanged) {
2468 mMetaState = newMetaState;
2469 updateLedState(false);
2470
2471 getContext()->updateGlobalMetaState();
2472 }
2473
2474 return metaStateChanged;
2475}
2476
Michael Wrightd02c5b62014-02-10 15:10:22 -08002477void KeyboardInputMapper::resetLedState() {
2478 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2479 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2480 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2481
2482 updateLedState(true);
2483}
2484
2485void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2486 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2487 ledState.on = false;
2488}
2489
2490void KeyboardInputMapper::updateLedState(bool reset) {
2491 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2492 AMETA_CAPS_LOCK_ON, reset);
2493 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2494 AMETA_NUM_LOCK_ON, reset);
2495 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2496 AMETA_SCROLL_LOCK_ON, reset);
2497}
2498
2499void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2500 int32_t led, int32_t modifier, bool reset) {
2501 if (ledState.avail) {
2502 bool desiredState = (mMetaState & modifier) != 0;
2503 if (reset || ledState.on != desiredState) {
2504 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2505 ledState.on = desiredState;
2506 }
2507 }
2508}
2509
2510
2511// --- CursorInputMapper ---
2512
2513CursorInputMapper::CursorInputMapper(InputDevice* device) :
2514 InputMapper(device) {
2515}
2516
2517CursorInputMapper::~CursorInputMapper() {
2518}
2519
2520uint32_t CursorInputMapper::getSources() {
2521 return mSource;
2522}
2523
2524void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2525 InputMapper::populateDeviceInfo(info);
2526
2527 if (mParameters.mode == Parameters::MODE_POINTER) {
2528 float minX, minY, maxX, maxY;
2529 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2530 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2531 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2532 }
2533 } else {
2534 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2535 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2536 }
2537 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2538
2539 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2540 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2541 }
2542 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2543 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2544 }
2545}
2546
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002547void CursorInputMapper::dump(std::string& dump) {
2548 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002549 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002550 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2551 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2552 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2553 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2554 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002555 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002556 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002557 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002558 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2559 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2560 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2561 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2562 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2563 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002564}
2565
2566void CursorInputMapper::configure(nsecs_t when,
2567 const InputReaderConfiguration* config, uint32_t changes) {
2568 InputMapper::configure(when, config, changes);
2569
2570 if (!changes) { // first time only
2571 mCursorScrollAccumulator.configure(getDevice());
2572
2573 // Configure basic parameters.
2574 configureParameters();
2575
2576 // Configure device mode.
2577 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002578 case Parameters::MODE_POINTER_RELATIVE:
2579 // Should not happen during first time configuration.
2580 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2581 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002582 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002583 case Parameters::MODE_POINTER:
2584 mSource = AINPUT_SOURCE_MOUSE;
2585 mXPrecision = 1.0f;
2586 mYPrecision = 1.0f;
2587 mXScale = 1.0f;
2588 mYScale = 1.0f;
2589 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2590 break;
2591 case Parameters::MODE_NAVIGATION:
2592 mSource = AINPUT_SOURCE_TRACKBALL;
2593 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2594 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2595 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2596 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2597 break;
2598 }
2599
2600 mVWheelScale = 1.0f;
2601 mHWheelScale = 1.0f;
2602 }
2603
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002604 if ((!changes && config->pointerCapture)
2605 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2606 if (config->pointerCapture) {
2607 if (mParameters.mode == Parameters::MODE_POINTER) {
2608 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2609 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2610 // Keep PointerController around in order to preserve the pointer position.
2611 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2612 } else {
2613 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2614 }
2615 } else {
2616 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2617 mParameters.mode = Parameters::MODE_POINTER;
2618 mSource = AINPUT_SOURCE_MOUSE;
2619 } else {
2620 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2621 }
2622 }
2623 bumpGeneration();
2624 if (changes) {
2625 getDevice()->notifyReset(when);
2626 }
2627 }
2628
Michael Wrightd02c5b62014-02-10 15:10:22 -08002629 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2630 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2631 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2632 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2633 }
2634
2635 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002636 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002637 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002638 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002639 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002640 if (internalViewport) {
2641 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002642 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002643 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002644
2645 // Update the PointerController if viewports changed.
2646 if (mParameters.hasAssociatedDisplay) {
2647 getPolicy()->obtainPointerController(getDeviceId());
2648 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 bumpGeneration();
2650 }
2651}
2652
2653void CursorInputMapper::configureParameters() {
2654 mParameters.mode = Parameters::MODE_POINTER;
2655 String8 cursorModeString;
2656 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2657 if (cursorModeString == "navigation") {
2658 mParameters.mode = Parameters::MODE_NAVIGATION;
2659 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2660 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2661 }
2662 }
2663
2664 mParameters.orientationAware = false;
2665 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2666 mParameters.orientationAware);
2667
2668 mParameters.hasAssociatedDisplay = false;
2669 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2670 mParameters.hasAssociatedDisplay = true;
2671 }
2672}
2673
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002674void CursorInputMapper::dumpParameters(std::string& dump) {
2675 dump += INDENT3 "Parameters:\n";
2676 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 toString(mParameters.hasAssociatedDisplay));
2678
2679 switch (mParameters.mode) {
2680 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002681 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002682 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002683 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002684 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002685 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002687 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002688 break;
2689 default:
2690 ALOG_ASSERT(false);
2691 }
2692
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002693 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002694 toString(mParameters.orientationAware));
2695}
2696
2697void CursorInputMapper::reset(nsecs_t when) {
2698 mButtonState = 0;
2699 mDownTime = 0;
2700
2701 mPointerVelocityControl.reset();
2702 mWheelXVelocityControl.reset();
2703 mWheelYVelocityControl.reset();
2704
2705 mCursorButtonAccumulator.reset(getDevice());
2706 mCursorMotionAccumulator.reset(getDevice());
2707 mCursorScrollAccumulator.reset(getDevice());
2708
2709 InputMapper::reset(when);
2710}
2711
2712void CursorInputMapper::process(const RawEvent* rawEvent) {
2713 mCursorButtonAccumulator.process(rawEvent);
2714 mCursorMotionAccumulator.process(rawEvent);
2715 mCursorScrollAccumulator.process(rawEvent);
2716
2717 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2718 sync(rawEvent->when);
2719 }
2720}
2721
2722void CursorInputMapper::sync(nsecs_t when) {
2723 int32_t lastButtonState = mButtonState;
2724 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2725 mButtonState = currentButtonState;
2726
2727 bool wasDown = isPointerDown(lastButtonState);
2728 bool down = isPointerDown(currentButtonState);
2729 bool downChanged;
2730 if (!wasDown && down) {
2731 mDownTime = when;
2732 downChanged = true;
2733 } else if (wasDown && !down) {
2734 downChanged = true;
2735 } else {
2736 downChanged = false;
2737 }
2738 nsecs_t downTime = mDownTime;
2739 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002740 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2741 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002742
2743 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2744 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2745 bool moved = deltaX != 0 || deltaY != 0;
2746
2747 // Rotate delta according to orientation if needed.
2748 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2749 && (deltaX != 0.0f || deltaY != 0.0f)) {
2750 rotateDelta(mOrientation, &deltaX, &deltaY);
2751 }
2752
2753 // Move the pointer.
2754 PointerProperties pointerProperties;
2755 pointerProperties.clear();
2756 pointerProperties.id = 0;
2757 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2758
2759 PointerCoords pointerCoords;
2760 pointerCoords.clear();
2761
2762 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2763 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2764 bool scrolled = vscroll != 0 || hscroll != 0;
2765
Yi Kong9b14ac62018-07-17 13:48:38 -07002766 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2767 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768
2769 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2770
2771 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002772 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002773 if (moved || scrolled || buttonsChanged) {
2774 mPointerController->setPresentation(
2775 PointerControllerInterface::PRESENTATION_POINTER);
2776
2777 if (moved) {
2778 mPointerController->move(deltaX, deltaY);
2779 }
2780
2781 if (buttonsChanged) {
2782 mPointerController->setButtonState(currentButtonState);
2783 }
2784
2785 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2786 }
2787
2788 float x, y;
2789 mPointerController->getPosition(&x, &y);
2790 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2791 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002792 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2793 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002794 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795 } else {
2796 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2797 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2798 displayId = ADISPLAY_ID_NONE;
2799 }
2800
2801 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2802
2803 // Moving an external trackball or mouse should wake the device.
2804 // We don't do this for internal cursor devices to prevent them from waking up
2805 // the device in your pocket.
2806 // TODO: Use the input device configuration to control this behavior more finely.
2807 uint32_t policyFlags = 0;
2808 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002809 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810 }
2811
2812 // Synthesize key down from buttons if needed.
2813 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002814 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815
2816 // Send motion event.
2817 if (downChanged || moved || scrolled || buttonsChanged) {
2818 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002819 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002820 int32_t motionEventAction;
2821 if (downChanged) {
2822 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002823 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002824 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2825 } else {
2826 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2827 }
2828
Michael Wright7b159c92015-05-14 14:48:03 +01002829 if (buttonsReleased) {
2830 BitSet32 released(buttonsReleased);
2831 while (!released.isEmpty()) {
2832 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2833 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002834 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2835 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002836 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002837 metaState, buttonState,
2838 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002839 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002840 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002841 getListener()->notifyMotion(&releaseArgs);
2842 }
2843 }
2844
Prabir Pradhan42611e02018-11-27 14:04:02 -08002845 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2846 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002847 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002848 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002849 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002850 getListener()->notifyMotion(&args);
2851
Michael Wright7b159c92015-05-14 14:48:03 +01002852 if (buttonsPressed) {
2853 BitSet32 pressed(buttonsPressed);
2854 while (!pressed.isEmpty()) {
2855 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2856 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002857 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2858 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002859 actionButton, 0, metaState, buttonState,
2860 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002861 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002862 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002863 getListener()->notifyMotion(&pressArgs);
2864 }
2865 }
2866
2867 ALOG_ASSERT(buttonState == currentButtonState);
2868
Michael Wrightd02c5b62014-02-10 15:10:22 -08002869 // Send hover move after UP to tell the application that the mouse is hovering now.
2870 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002871 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002872 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2873 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002874 metaState, currentButtonState,
2875 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002876 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002877 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 getListener()->notifyMotion(&hoverArgs);
2879 }
2880
2881 // Send scroll events.
2882 if (scrolled) {
2883 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2884 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2885
Prabir Pradhan42611e02018-11-27 14:04:02 -08002886 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2887 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002888 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08002889 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002890 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002891 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002892 getListener()->notifyMotion(&scrollArgs);
2893 }
2894 }
2895
2896 // Synthesize key up from buttons if needed.
2897 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002898 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002899
2900 mCursorMotionAccumulator.finishSync();
2901 mCursorScrollAccumulator.finishSync();
2902}
2903
2904int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2905 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2906 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2907 } else {
2908 return AKEY_STATE_UNKNOWN;
2909 }
2910}
2911
2912void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002913 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002914 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2915 }
2916}
2917
Prashant Malani1941ff52015-08-11 18:29:28 -07002918// --- RotaryEncoderInputMapper ---
2919
2920RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002921 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002922 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2923}
2924
2925RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2926}
2927
2928uint32_t RotaryEncoderInputMapper::getSources() {
2929 return mSource;
2930}
2931
2932void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2933 InputMapper::populateDeviceInfo(info);
2934
2935 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002936 float res = 0.0f;
2937 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2938 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2939 }
2940 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2941 mScalingFactor)) {
2942 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2943 "default to 1.0!\n");
2944 mScalingFactor = 1.0f;
2945 }
2946 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2947 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002948 }
2949}
2950
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002951void RotaryEncoderInputMapper::dump(std::string& dump) {
2952 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2953 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002954 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2955}
2956
2957void RotaryEncoderInputMapper::configure(nsecs_t when,
2958 const InputReaderConfiguration* config, uint32_t changes) {
2959 InputMapper::configure(when, config, changes);
2960 if (!changes) {
2961 mRotaryEncoderScrollAccumulator.configure(getDevice());
2962 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002963 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002964 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002965 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002966 if (internalViewport) {
2967 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002968 } else {
2969 mOrientation = DISPLAY_ORIENTATION_0;
2970 }
2971 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002972}
2973
2974void RotaryEncoderInputMapper::reset(nsecs_t when) {
2975 mRotaryEncoderScrollAccumulator.reset(getDevice());
2976
2977 InputMapper::reset(when);
2978}
2979
2980void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2981 mRotaryEncoderScrollAccumulator.process(rawEvent);
2982
2983 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2984 sync(rawEvent->when);
2985 }
2986}
2987
2988void RotaryEncoderInputMapper::sync(nsecs_t when) {
2989 PointerCoords pointerCoords;
2990 pointerCoords.clear();
2991
2992 PointerProperties pointerProperties;
2993 pointerProperties.clear();
2994 pointerProperties.id = 0;
2995 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2996
2997 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2998 bool scrolled = scroll != 0;
2999
3000 // This is not a pointer, so it's not associated with a display.
3001 int32_t displayId = ADISPLAY_ID_NONE;
3002
3003 // Moving the rotary encoder should wake the device (if specified).
3004 uint32_t policyFlags = 0;
3005 if (scrolled && getDevice()->isExternal()) {
3006 policyFlags |= POLICY_FLAG_WAKE;
3007 }
3008
Ivan Podogovad437252016-09-29 16:29:55 +01003009 if (mOrientation == DISPLAY_ORIENTATION_180) {
3010 scroll = -scroll;
3011 }
3012
Prashant Malani1941ff52015-08-11 18:29:28 -07003013 // Send motion event.
3014 if (scrolled) {
3015 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003016 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003017
Prabir Pradhan42611e02018-11-27 14:04:02 -08003018 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3019 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08003020 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, /* buttonState */ 0,
3021 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003022 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003023 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003024 getListener()->notifyMotion(&scrollArgs);
3025 }
3026
3027 mRotaryEncoderScrollAccumulator.finishSync();
3028}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029
3030// --- TouchInputMapper ---
3031
3032TouchInputMapper::TouchInputMapper(InputDevice* device) :
3033 InputMapper(device),
3034 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3035 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003036 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003037 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3038}
3039
3040TouchInputMapper::~TouchInputMapper() {
3041}
3042
3043uint32_t TouchInputMapper::getSources() {
3044 return mSource;
3045}
3046
3047void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3048 InputMapper::populateDeviceInfo(info);
3049
3050 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3051 info->addMotionRange(mOrientedRanges.x);
3052 info->addMotionRange(mOrientedRanges.y);
3053 info->addMotionRange(mOrientedRanges.pressure);
3054
3055 if (mOrientedRanges.haveSize) {
3056 info->addMotionRange(mOrientedRanges.size);
3057 }
3058
3059 if (mOrientedRanges.haveTouchSize) {
3060 info->addMotionRange(mOrientedRanges.touchMajor);
3061 info->addMotionRange(mOrientedRanges.touchMinor);
3062 }
3063
3064 if (mOrientedRanges.haveToolSize) {
3065 info->addMotionRange(mOrientedRanges.toolMajor);
3066 info->addMotionRange(mOrientedRanges.toolMinor);
3067 }
3068
3069 if (mOrientedRanges.haveOrientation) {
3070 info->addMotionRange(mOrientedRanges.orientation);
3071 }
3072
3073 if (mOrientedRanges.haveDistance) {
3074 info->addMotionRange(mOrientedRanges.distance);
3075 }
3076
3077 if (mOrientedRanges.haveTilt) {
3078 info->addMotionRange(mOrientedRanges.tilt);
3079 }
3080
3081 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3082 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3083 0.0f);
3084 }
3085 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3086 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3087 0.0f);
3088 }
3089 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3090 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3091 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3092 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3093 x.fuzz, x.resolution);
3094 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3095 y.fuzz, y.resolution);
3096 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3097 x.fuzz, x.resolution);
3098 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3099 y.fuzz, y.resolution);
3100 }
3101 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3102 }
3103}
3104
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003105void TouchInputMapper::dump(std::string& dump) {
3106 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003107 dumpParameters(dump);
3108 dumpVirtualKeys(dump);
3109 dumpRawPointerAxes(dump);
3110 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003111 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003112 dumpSurface(dump);
3113
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003114 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3115 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3116 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3117 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3118 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3119 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3120 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3121 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3122 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3123 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3124 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3125 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3126 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3127 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3128 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3129 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3130 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003131
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003132 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3133 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003134 mLastRawState.rawPointerData.pointerCount);
3135 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3136 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003137 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3139 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3140 "toolType=%d, isHovering=%s\n", i,
3141 pointer.id, pointer.x, pointer.y, pointer.pressure,
3142 pointer.touchMajor, pointer.touchMinor,
3143 pointer.toolMajor, pointer.toolMinor,
3144 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3145 pointer.toolType, toString(pointer.isHovering));
3146 }
3147
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003148 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3149 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003150 mLastCookedState.cookedPointerData.pointerCount);
3151 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3152 const PointerProperties& pointerProperties =
3153 mLastCookedState.cookedPointerData.pointerProperties[i];
3154 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003155 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3157 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3158 "toolType=%d, isHovering=%s\n", i,
3159 pointerProperties.id,
3160 pointerCoords.getX(),
3161 pointerCoords.getY(),
3162 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3163 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3164 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3165 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3166 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3167 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3168 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3169 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3170 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003171 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 }
3173
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003174 dump += INDENT3 "Stylus Fusion:\n";
3175 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003176 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3178 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003179 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003180 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003181 dumpStylusState(dump, mExternalStylusState);
3182
Michael Wrightd02c5b62014-02-10 15:10:22 -08003183 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003184 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3185 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003187 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003188 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003189 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003190 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003191 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003192 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003193 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003194 mPointerGestureMaxSwipeWidth);
3195 }
3196}
3197
Santos Cordonfa5cf462017-04-05 10:37:00 -07003198const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3199 switch (deviceMode) {
3200 case DEVICE_MODE_DISABLED:
3201 return "disabled";
3202 case DEVICE_MODE_DIRECT:
3203 return "direct";
3204 case DEVICE_MODE_UNSCALED:
3205 return "unscaled";
3206 case DEVICE_MODE_NAVIGATION:
3207 return "navigation";
3208 case DEVICE_MODE_POINTER:
3209 return "pointer";
3210 }
3211 return "unknown";
3212}
3213
Michael Wrightd02c5b62014-02-10 15:10:22 -08003214void TouchInputMapper::configure(nsecs_t when,
3215 const InputReaderConfiguration* config, uint32_t changes) {
3216 InputMapper::configure(when, config, changes);
3217
3218 mConfig = *config;
3219
3220 if (!changes) { // first time only
3221 // Configure basic parameters.
3222 configureParameters();
3223
3224 // Configure common accumulators.
3225 mCursorScrollAccumulator.configure(getDevice());
3226 mTouchButtonAccumulator.configure(getDevice());
3227
3228 // Configure absolute axis information.
3229 configureRawPointerAxes();
3230
3231 // Prepare input device calibration.
3232 parseCalibration();
3233 resolveCalibration();
3234 }
3235
Michael Wright842500e2015-03-13 17:32:02 -07003236 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003237 // Update location calibration to reflect current settings
3238 updateAffineTransformation();
3239 }
3240
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3242 // Update pointer speed.
3243 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3244 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3245 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3246 }
3247
3248 bool resetNeeded = false;
3249 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3250 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003251 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3252 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003253 // Configure device sources, surface dimensions, orientation and
3254 // scaling factors.
3255 configureSurface(when, &resetNeeded);
3256 }
3257
3258 if (changes && resetNeeded) {
3259 // Send reset, unless this is the first time the device has been configured,
3260 // in which case the reader will call reset itself after all mappers are ready.
3261 getDevice()->notifyReset(when);
3262 }
3263}
3264
Michael Wright842500e2015-03-13 17:32:02 -07003265void TouchInputMapper::resolveExternalStylusPresence() {
3266 Vector<InputDeviceInfo> devices;
3267 mContext->getExternalStylusDevices(devices);
3268 mExternalStylusConnected = !devices.isEmpty();
3269
3270 if (!mExternalStylusConnected) {
3271 resetExternalStylus();
3272 }
3273}
3274
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275void TouchInputMapper::configureParameters() {
3276 // Use the pointer presentation mode for devices that do not support distinct
3277 // multitouch. The spot-based presentation relies on being able to accurately
3278 // locate two or more fingers on the touch pad.
3279 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003280 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281
3282 String8 gestureModeString;
3283 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3284 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003285 if (gestureModeString == "single-touch") {
3286 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3287 } else if (gestureModeString == "multi-touch") {
3288 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003289 } else if (gestureModeString != "default") {
3290 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3291 }
3292 }
3293
3294 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3295 // The device is a touch screen.
3296 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3297 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3298 // The device is a pointing device like a track pad.
3299 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3300 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3301 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3302 // The device is a cursor device with a touch pad attached.
3303 // By default don't use the touch pad to move the pointer.
3304 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3305 } else {
3306 // The device is a touch pad of unknown purpose.
3307 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3308 }
3309
3310 mParameters.hasButtonUnderPad=
3311 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3312
3313 String8 deviceTypeString;
3314 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3315 deviceTypeString)) {
3316 if (deviceTypeString == "touchScreen") {
3317 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3318 } else if (deviceTypeString == "touchPad") {
3319 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3320 } else if (deviceTypeString == "touchNavigation") {
3321 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3322 } else if (deviceTypeString == "pointer") {
3323 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3324 } else if (deviceTypeString != "default") {
3325 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3326 }
3327 }
3328
3329 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3330 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3331 mParameters.orientationAware);
3332
3333 mParameters.hasAssociatedDisplay = false;
3334 mParameters.associatedDisplayIsExternal = false;
3335 if (mParameters.orientationAware
3336 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3337 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3338 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003339 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3340 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003341 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003342 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003343 uniqueDisplayId);
3344 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003345 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003346 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003347 if (getDevice()->getAssociatedDisplayPort()) {
3348 mParameters.hasAssociatedDisplay = true;
3349 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003350
3351 // Initial downs on external touch devices should wake the device.
3352 // Normally we don't do this for internal touch screens to prevent them from waking
3353 // up in your pocket but you can enable it using the input device configuration.
3354 mParameters.wake = getDevice()->isExternal();
3355 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3356 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357}
3358
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003359void TouchInputMapper::dumpParameters(std::string& dump) {
3360 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361
3362 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003363 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003364 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003366 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003367 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 break;
3369 default:
3370 assert(false);
3371 }
3372
3373 switch (mParameters.deviceType) {
3374 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003375 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003376 break;
3377 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003378 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003379 break;
3380 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003381 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 break;
3383 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003384 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003385 break;
3386 default:
3387 ALOG_ASSERT(false);
3388 }
3389
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003390 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003391 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003393 toString(mParameters.associatedDisplayIsExternal),
3394 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003395 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003396 toString(mParameters.orientationAware));
3397}
3398
3399void TouchInputMapper::configureRawPointerAxes() {
3400 mRawPointerAxes.clear();
3401}
3402
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003403void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3404 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3406 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3407 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3408 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3410 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3411 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3412 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3413 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3414 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3415 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3416 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3417 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3418}
3419
Michael Wright842500e2015-03-13 17:32:02 -07003420bool TouchInputMapper::hasExternalStylus() const {
3421 return mExternalStylusConnected;
3422}
3423
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003424/**
3425 * Determine which DisplayViewport to use.
3426 * 1. If display port is specified, return the matching viewport. If matching viewport not
3427 * found, then return.
3428 * 2. If a device has associated display, get the matching viewport by either unique id or by
3429 * the display type (internal or external).
3430 * 3. Otherwise, use a non-display viewport.
3431 */
3432std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3433 if (mParameters.hasAssociatedDisplay) {
3434 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3435 if (displayPort) {
3436 // Find the viewport that contains the same port
3437 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3438 if (!v) {
3439 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3440 "but the corresponding viewport is not found.",
3441 getDeviceName().c_str(), *displayPort);
3442 }
3443 return v;
3444 }
3445
3446 if (!mParameters.uniqueDisplayId.empty()) {
3447 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3448 }
3449
3450 ViewportType viewportTypeToUse;
3451 if (mParameters.associatedDisplayIsExternal) {
3452 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3453 } else {
3454 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3455 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003456
3457 std::optional<DisplayViewport> viewport =
3458 mConfig.getDisplayViewportByType(viewportTypeToUse);
3459 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3460 ALOGW("Input device %s should be associated with external display, "
3461 "fallback to internal one for the external viewport is not found.",
3462 getDeviceName().c_str());
3463 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3464 }
3465
3466 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003467 }
3468
3469 DisplayViewport newViewport;
3470 // Raw width and height in the natural orientation.
3471 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3472 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3473 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3474 return std::make_optional(newViewport);
3475}
3476
Michael Wrightd02c5b62014-02-10 15:10:22 -08003477void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3478 int32_t oldDeviceMode = mDeviceMode;
3479
Michael Wright842500e2015-03-13 17:32:02 -07003480 resolveExternalStylusPresence();
3481
Michael Wrightd02c5b62014-02-10 15:10:22 -08003482 // Determine device mode.
3483 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3484 && mConfig.pointerGesturesEnabled) {
3485 mSource = AINPUT_SOURCE_MOUSE;
3486 mDeviceMode = DEVICE_MODE_POINTER;
3487 if (hasStylus()) {
3488 mSource |= AINPUT_SOURCE_STYLUS;
3489 }
3490 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3491 && mParameters.hasAssociatedDisplay) {
3492 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3493 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003494 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003495 mSource |= AINPUT_SOURCE_STYLUS;
3496 }
Michael Wright2f78b682015-06-12 15:25:08 +01003497 if (hasExternalStylus()) {
3498 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3499 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003500 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3501 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3502 mDeviceMode = DEVICE_MODE_NAVIGATION;
3503 } else {
3504 mSource = AINPUT_SOURCE_TOUCHPAD;
3505 mDeviceMode = DEVICE_MODE_UNSCALED;
3506 }
3507
3508 // Ensure we have valid X and Y axes.
3509 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003510 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003511 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003512 mDeviceMode = DEVICE_MODE_DISABLED;
3513 return;
3514 }
3515
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003516 // Get associated display dimensions.
3517 std::optional<DisplayViewport> newViewport = findViewport();
3518 if (!newViewport) {
3519 ALOGI("Touch device '%s' could not query the properties of its associated "
3520 "display. The device will be inoperable until the display size "
3521 "becomes available.",
3522 getDeviceName().c_str());
3523 mDeviceMode = DEVICE_MODE_DISABLED;
3524 return;
3525 }
3526
Michael Wrightd02c5b62014-02-10 15:10:22 -08003527 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003528 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3529 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003530
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003531 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003532 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003533 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534
3535 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3536 // Convert rotated viewport to natural surface coordinates.
3537 int32_t naturalLogicalWidth, naturalLogicalHeight;
3538 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3539 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3540 int32_t naturalDeviceWidth, naturalDeviceHeight;
3541 switch (mViewport.orientation) {
3542 case DISPLAY_ORIENTATION_90:
3543 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3544 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3545 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3546 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3547 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3548 naturalPhysicalTop = mViewport.physicalLeft;
3549 naturalDeviceWidth = mViewport.deviceHeight;
3550 naturalDeviceHeight = mViewport.deviceWidth;
3551 break;
3552 case DISPLAY_ORIENTATION_180:
3553 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3554 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3555 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3556 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3557 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3558 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3559 naturalDeviceWidth = mViewport.deviceWidth;
3560 naturalDeviceHeight = mViewport.deviceHeight;
3561 break;
3562 case DISPLAY_ORIENTATION_270:
3563 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3564 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3565 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3566 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3567 naturalPhysicalLeft = mViewport.physicalTop;
3568 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3569 naturalDeviceWidth = mViewport.deviceHeight;
3570 naturalDeviceHeight = mViewport.deviceWidth;
3571 break;
3572 case DISPLAY_ORIENTATION_0:
3573 default:
3574 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3575 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3576 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3577 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3578 naturalPhysicalLeft = mViewport.physicalLeft;
3579 naturalPhysicalTop = mViewport.physicalTop;
3580 naturalDeviceWidth = mViewport.deviceWidth;
3581 naturalDeviceHeight = mViewport.deviceHeight;
3582 break;
3583 }
3584
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003585 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3586 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3587 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3588 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3589 }
3590
Michael Wright358bcc72018-08-21 04:01:07 +01003591 mPhysicalWidth = naturalPhysicalWidth;
3592 mPhysicalHeight = naturalPhysicalHeight;
3593 mPhysicalLeft = naturalPhysicalLeft;
3594 mPhysicalTop = naturalPhysicalTop;
3595
Michael Wrightd02c5b62014-02-10 15:10:22 -08003596 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3597 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3598 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3599 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3600
3601 mSurfaceOrientation = mParameters.orientationAware ?
3602 mViewport.orientation : DISPLAY_ORIENTATION_0;
3603 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003604 mPhysicalWidth = rawWidth;
3605 mPhysicalHeight = rawHeight;
3606 mPhysicalLeft = 0;
3607 mPhysicalTop = 0;
3608
Michael Wrightd02c5b62014-02-10 15:10:22 -08003609 mSurfaceWidth = rawWidth;
3610 mSurfaceHeight = rawHeight;
3611 mSurfaceLeft = 0;
3612 mSurfaceTop = 0;
3613 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3614 }
3615 }
3616
3617 // If moving between pointer modes, need to reset some state.
3618 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3619 if (deviceModeChanged) {
3620 mOrientedRanges.clear();
3621 }
3622
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003623 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003624 if (mDeviceMode == DEVICE_MODE_POINTER ||
3625 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003626 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003627 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3628 }
3629 } else {
3630 mPointerController.clear();
3631 }
3632
3633 if (viewportChanged || deviceModeChanged) {
3634 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3635 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003636 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003637 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3638
3639 // Configure X and Y factors.
3640 mXScale = float(mSurfaceWidth) / rawWidth;
3641 mYScale = float(mSurfaceHeight) / rawHeight;
3642 mXTranslate = -mSurfaceLeft;
3643 mYTranslate = -mSurfaceTop;
3644 mXPrecision = 1.0f / mXScale;
3645 mYPrecision = 1.0f / mYScale;
3646
3647 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3648 mOrientedRanges.x.source = mSource;
3649 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3650 mOrientedRanges.y.source = mSource;
3651
3652 configureVirtualKeys();
3653
3654 // Scale factor for terms that are not oriented in a particular axis.
3655 // If the pixels are square then xScale == yScale otherwise we fake it
3656 // by choosing an average.
3657 mGeometricScale = avg(mXScale, mYScale);
3658
3659 // Size of diagonal axis.
3660 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3661
3662 // Size factors.
3663 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3664 if (mRawPointerAxes.touchMajor.valid
3665 && mRawPointerAxes.touchMajor.maxValue != 0) {
3666 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3667 } else if (mRawPointerAxes.toolMajor.valid
3668 && mRawPointerAxes.toolMajor.maxValue != 0) {
3669 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3670 } else {
3671 mSizeScale = 0.0f;
3672 }
3673
3674 mOrientedRanges.haveTouchSize = true;
3675 mOrientedRanges.haveToolSize = true;
3676 mOrientedRanges.haveSize = true;
3677
3678 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3679 mOrientedRanges.touchMajor.source = mSource;
3680 mOrientedRanges.touchMajor.min = 0;
3681 mOrientedRanges.touchMajor.max = diagonalSize;
3682 mOrientedRanges.touchMajor.flat = 0;
3683 mOrientedRanges.touchMajor.fuzz = 0;
3684 mOrientedRanges.touchMajor.resolution = 0;
3685
3686 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3687 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3688
3689 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3690 mOrientedRanges.toolMajor.source = mSource;
3691 mOrientedRanges.toolMajor.min = 0;
3692 mOrientedRanges.toolMajor.max = diagonalSize;
3693 mOrientedRanges.toolMajor.flat = 0;
3694 mOrientedRanges.toolMajor.fuzz = 0;
3695 mOrientedRanges.toolMajor.resolution = 0;
3696
3697 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3698 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3699
3700 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3701 mOrientedRanges.size.source = mSource;
3702 mOrientedRanges.size.min = 0;
3703 mOrientedRanges.size.max = 1.0;
3704 mOrientedRanges.size.flat = 0;
3705 mOrientedRanges.size.fuzz = 0;
3706 mOrientedRanges.size.resolution = 0;
3707 } else {
3708 mSizeScale = 0.0f;
3709 }
3710
3711 // Pressure factors.
3712 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003713 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003714 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3715 || mCalibration.pressureCalibration
3716 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3717 if (mCalibration.havePressureScale) {
3718 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003719 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003720 } else if (mRawPointerAxes.pressure.valid
3721 && mRawPointerAxes.pressure.maxValue != 0) {
3722 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3723 }
3724 }
3725
3726 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3727 mOrientedRanges.pressure.source = mSource;
3728 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003729 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003730 mOrientedRanges.pressure.flat = 0;
3731 mOrientedRanges.pressure.fuzz = 0;
3732 mOrientedRanges.pressure.resolution = 0;
3733
3734 // Tilt
3735 mTiltXCenter = 0;
3736 mTiltXScale = 0;
3737 mTiltYCenter = 0;
3738 mTiltYScale = 0;
3739 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3740 if (mHaveTilt) {
3741 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3742 mRawPointerAxes.tiltX.maxValue);
3743 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3744 mRawPointerAxes.tiltY.maxValue);
3745 mTiltXScale = M_PI / 180;
3746 mTiltYScale = M_PI / 180;
3747
3748 mOrientedRanges.haveTilt = true;
3749
3750 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3751 mOrientedRanges.tilt.source = mSource;
3752 mOrientedRanges.tilt.min = 0;
3753 mOrientedRanges.tilt.max = M_PI_2;
3754 mOrientedRanges.tilt.flat = 0;
3755 mOrientedRanges.tilt.fuzz = 0;
3756 mOrientedRanges.tilt.resolution = 0;
3757 }
3758
3759 // Orientation
3760 mOrientationScale = 0;
3761 if (mHaveTilt) {
3762 mOrientedRanges.haveOrientation = true;
3763
3764 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3765 mOrientedRanges.orientation.source = mSource;
3766 mOrientedRanges.orientation.min = -M_PI;
3767 mOrientedRanges.orientation.max = M_PI;
3768 mOrientedRanges.orientation.flat = 0;
3769 mOrientedRanges.orientation.fuzz = 0;
3770 mOrientedRanges.orientation.resolution = 0;
3771 } else if (mCalibration.orientationCalibration !=
3772 Calibration::ORIENTATION_CALIBRATION_NONE) {
3773 if (mCalibration.orientationCalibration
3774 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3775 if (mRawPointerAxes.orientation.valid) {
3776 if (mRawPointerAxes.orientation.maxValue > 0) {
3777 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3778 } else if (mRawPointerAxes.orientation.minValue < 0) {
3779 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3780 } else {
3781 mOrientationScale = 0;
3782 }
3783 }
3784 }
3785
3786 mOrientedRanges.haveOrientation = true;
3787
3788 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3789 mOrientedRanges.orientation.source = mSource;
3790 mOrientedRanges.orientation.min = -M_PI_2;
3791 mOrientedRanges.orientation.max = M_PI_2;
3792 mOrientedRanges.orientation.flat = 0;
3793 mOrientedRanges.orientation.fuzz = 0;
3794 mOrientedRanges.orientation.resolution = 0;
3795 }
3796
3797 // Distance
3798 mDistanceScale = 0;
3799 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3800 if (mCalibration.distanceCalibration
3801 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3802 if (mCalibration.haveDistanceScale) {
3803 mDistanceScale = mCalibration.distanceScale;
3804 } else {
3805 mDistanceScale = 1.0f;
3806 }
3807 }
3808
3809 mOrientedRanges.haveDistance = true;
3810
3811 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3812 mOrientedRanges.distance.source = mSource;
3813 mOrientedRanges.distance.min =
3814 mRawPointerAxes.distance.minValue * mDistanceScale;
3815 mOrientedRanges.distance.max =
3816 mRawPointerAxes.distance.maxValue * mDistanceScale;
3817 mOrientedRanges.distance.flat = 0;
3818 mOrientedRanges.distance.fuzz =
3819 mRawPointerAxes.distance.fuzz * mDistanceScale;
3820 mOrientedRanges.distance.resolution = 0;
3821 }
3822
3823 // Compute oriented precision, scales and ranges.
3824 // Note that the maximum value reported is an inclusive maximum value so it is one
3825 // unit less than the total width or height of surface.
3826 switch (mSurfaceOrientation) {
3827 case DISPLAY_ORIENTATION_90:
3828 case DISPLAY_ORIENTATION_270:
3829 mOrientedXPrecision = mYPrecision;
3830 mOrientedYPrecision = mXPrecision;
3831
3832 mOrientedRanges.x.min = mYTranslate;
3833 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3834 mOrientedRanges.x.flat = 0;
3835 mOrientedRanges.x.fuzz = 0;
3836 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3837
3838 mOrientedRanges.y.min = mXTranslate;
3839 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3840 mOrientedRanges.y.flat = 0;
3841 mOrientedRanges.y.fuzz = 0;
3842 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3843 break;
3844
3845 default:
3846 mOrientedXPrecision = mXPrecision;
3847 mOrientedYPrecision = mYPrecision;
3848
3849 mOrientedRanges.x.min = mXTranslate;
3850 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3851 mOrientedRanges.x.flat = 0;
3852 mOrientedRanges.x.fuzz = 0;
3853 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3854
3855 mOrientedRanges.y.min = mYTranslate;
3856 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3857 mOrientedRanges.y.flat = 0;
3858 mOrientedRanges.y.fuzz = 0;
3859 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3860 break;
3861 }
3862
Jason Gerecke71b16e82014-03-10 09:47:59 -07003863 // Location
3864 updateAffineTransformation();
3865
Michael Wrightd02c5b62014-02-10 15:10:22 -08003866 if (mDeviceMode == DEVICE_MODE_POINTER) {
3867 // Compute pointer gesture detection parameters.
3868 float rawDiagonal = hypotf(rawWidth, rawHeight);
3869 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3870
3871 // Scale movements such that one whole swipe of the touch pad covers a
3872 // given area relative to the diagonal size of the display when no acceleration
3873 // is applied.
3874 // Assume that the touch pad has a square aspect ratio such that movements in
3875 // X and Y of the same number of raw units cover the same physical distance.
3876 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3877 * displayDiagonal / rawDiagonal;
3878 mPointerYMovementScale = mPointerXMovementScale;
3879
3880 // Scale zooms to cover a smaller range of the display than movements do.
3881 // This value determines the area around the pointer that is affected by freeform
3882 // pointer gestures.
3883 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3884 * displayDiagonal / rawDiagonal;
3885 mPointerYZoomScale = mPointerXZoomScale;
3886
3887 // Max width between pointers to detect a swipe gesture is more than some fraction
3888 // of the diagonal axis of the touch pad. Touches that are wider than this are
3889 // translated into freeform gestures.
3890 mPointerGestureMaxSwipeWidth =
3891 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3892
3893 // Abort current pointer usages because the state has changed.
3894 abortPointerUsage(when, 0 /*policyFlags*/);
3895 }
3896
3897 // Inform the dispatcher about the changes.
3898 *outResetNeeded = true;
3899 bumpGeneration();
3900 }
3901}
3902
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003903void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003904 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003905 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3906 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3907 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3908 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003909 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3910 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3911 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3912 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003913 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003914}
3915
3916void TouchInputMapper::configureVirtualKeys() {
3917 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3918 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3919
3920 mVirtualKeys.clear();
3921
3922 if (virtualKeyDefinitions.size() == 0) {
3923 return;
3924 }
3925
3926 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3927
3928 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3929 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003930 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3931 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003932
3933 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3934 const VirtualKeyDefinition& virtualKeyDefinition =
3935 virtualKeyDefinitions[i];
3936
3937 mVirtualKeys.add();
3938 VirtualKey& virtualKey = mVirtualKeys.editTop();
3939
3940 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3941 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003942 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003944 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3945 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003946 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3947 virtualKey.scanCode);
3948 mVirtualKeys.pop(); // drop the key
3949 continue;
3950 }
3951
3952 virtualKey.keyCode = keyCode;
3953 virtualKey.flags = flags;
3954
3955 // convert the key definition's display coordinates into touch coordinates for a hit box
3956 int32_t halfWidth = virtualKeyDefinition.width / 2;
3957 int32_t halfHeight = virtualKeyDefinition.height / 2;
3958
3959 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3960 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3961 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3962 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3963 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3964 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3965 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3966 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3967 }
3968}
3969
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003970void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003972 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003973
3974 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3975 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003976 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003977 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3978 i, virtualKey.scanCode, virtualKey.keyCode,
3979 virtualKey.hitLeft, virtualKey.hitRight,
3980 virtualKey.hitTop, virtualKey.hitBottom);
3981 }
3982 }
3983}
3984
3985void TouchInputMapper::parseCalibration() {
3986 const PropertyMap& in = getDevice()->getConfiguration();
3987 Calibration& out = mCalibration;
3988
3989 // Size
3990 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3991 String8 sizeCalibrationString;
3992 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3993 if (sizeCalibrationString == "none") {
3994 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3995 } else if (sizeCalibrationString == "geometric") {
3996 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3997 } else if (sizeCalibrationString == "diameter") {
3998 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3999 } else if (sizeCalibrationString == "box") {
4000 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4001 } else if (sizeCalibrationString == "area") {
4002 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4003 } else if (sizeCalibrationString != "default") {
4004 ALOGW("Invalid value for touch.size.calibration: '%s'",
4005 sizeCalibrationString.string());
4006 }
4007 }
4008
4009 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4010 out.sizeScale);
4011 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4012 out.sizeBias);
4013 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4014 out.sizeIsSummed);
4015
4016 // Pressure
4017 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4018 String8 pressureCalibrationString;
4019 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4020 if (pressureCalibrationString == "none") {
4021 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4022 } else if (pressureCalibrationString == "physical") {
4023 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4024 } else if (pressureCalibrationString == "amplitude") {
4025 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4026 } else if (pressureCalibrationString != "default") {
4027 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4028 pressureCalibrationString.string());
4029 }
4030 }
4031
4032 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4033 out.pressureScale);
4034
4035 // Orientation
4036 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4037 String8 orientationCalibrationString;
4038 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4039 if (orientationCalibrationString == "none") {
4040 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4041 } else if (orientationCalibrationString == "interpolated") {
4042 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4043 } else if (orientationCalibrationString == "vector") {
4044 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4045 } else if (orientationCalibrationString != "default") {
4046 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4047 orientationCalibrationString.string());
4048 }
4049 }
4050
4051 // Distance
4052 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4053 String8 distanceCalibrationString;
4054 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4055 if (distanceCalibrationString == "none") {
4056 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4057 } else if (distanceCalibrationString == "scaled") {
4058 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4059 } else if (distanceCalibrationString != "default") {
4060 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4061 distanceCalibrationString.string());
4062 }
4063 }
4064
4065 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4066 out.distanceScale);
4067
4068 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4069 String8 coverageCalibrationString;
4070 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4071 if (coverageCalibrationString == "none") {
4072 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4073 } else if (coverageCalibrationString == "box") {
4074 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4075 } else if (coverageCalibrationString != "default") {
4076 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4077 coverageCalibrationString.string());
4078 }
4079 }
4080}
4081
4082void TouchInputMapper::resolveCalibration() {
4083 // Size
4084 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4085 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4086 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4087 }
4088 } else {
4089 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4090 }
4091
4092 // Pressure
4093 if (mRawPointerAxes.pressure.valid) {
4094 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4095 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4096 }
4097 } else {
4098 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4099 }
4100
4101 // Orientation
4102 if (mRawPointerAxes.orientation.valid) {
4103 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4104 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4105 }
4106 } else {
4107 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4108 }
4109
4110 // Distance
4111 if (mRawPointerAxes.distance.valid) {
4112 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4113 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4114 }
4115 } else {
4116 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4117 }
4118
4119 // Coverage
4120 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4121 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4122 }
4123}
4124
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004125void TouchInputMapper::dumpCalibration(std::string& dump) {
4126 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127
4128 // Size
4129 switch (mCalibration.sizeCalibration) {
4130 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004131 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 break;
4133 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004134 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004135 break;
4136 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004137 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004138 break;
4139 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004140 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004141 break;
4142 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004143 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 break;
4145 default:
4146 ALOG_ASSERT(false);
4147 }
4148
4149 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004150 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004151 mCalibration.sizeScale);
4152 }
4153
4154 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004155 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004156 mCalibration.sizeBias);
4157 }
4158
4159 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004160 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004161 toString(mCalibration.sizeIsSummed));
4162 }
4163
4164 // Pressure
4165 switch (mCalibration.pressureCalibration) {
4166 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004167 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004168 break;
4169 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004170 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004171 break;
4172 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004173 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 break;
4175 default:
4176 ALOG_ASSERT(false);
4177 }
4178
4179 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004180 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004181 mCalibration.pressureScale);
4182 }
4183
4184 // Orientation
4185 switch (mCalibration.orientationCalibration) {
4186 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004187 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 break;
4189 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004190 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004191 break;
4192 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004193 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 break;
4195 default:
4196 ALOG_ASSERT(false);
4197 }
4198
4199 // Distance
4200 switch (mCalibration.distanceCalibration) {
4201 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004202 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004203 break;
4204 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004205 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004206 break;
4207 default:
4208 ALOG_ASSERT(false);
4209 }
4210
4211 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004212 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 mCalibration.distanceScale);
4214 }
4215
4216 switch (mCalibration.coverageCalibration) {
4217 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004218 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004219 break;
4220 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004221 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004222 break;
4223 default:
4224 ALOG_ASSERT(false);
4225 }
4226}
4227
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004228void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4229 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004230
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004231 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4232 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4233 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4234 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4235 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4236 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004237}
4238
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004239void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004240 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4241 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004242}
4243
Michael Wrightd02c5b62014-02-10 15:10:22 -08004244void TouchInputMapper::reset(nsecs_t when) {
4245 mCursorButtonAccumulator.reset(getDevice());
4246 mCursorScrollAccumulator.reset(getDevice());
4247 mTouchButtonAccumulator.reset(getDevice());
4248
4249 mPointerVelocityControl.reset();
4250 mWheelXVelocityControl.reset();
4251 mWheelYVelocityControl.reset();
4252
Michael Wright842500e2015-03-13 17:32:02 -07004253 mRawStatesPending.clear();
4254 mCurrentRawState.clear();
4255 mCurrentCookedState.clear();
4256 mLastRawState.clear();
4257 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004258 mPointerUsage = POINTER_USAGE_NONE;
4259 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004260 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004261 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004262 mDownTime = 0;
4263
4264 mCurrentVirtualKey.down = false;
4265
4266 mPointerGesture.reset();
4267 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004268 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004269
Yi Kong9b14ac62018-07-17 13:48:38 -07004270 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004271 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4272 mPointerController->clearSpots();
4273 }
4274
4275 InputMapper::reset(when);
4276}
4277
Michael Wright842500e2015-03-13 17:32:02 -07004278void TouchInputMapper::resetExternalStylus() {
4279 mExternalStylusState.clear();
4280 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004281 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004282 mExternalStylusDataPending = false;
4283}
4284
Michael Wright43fd19f2015-04-21 19:02:58 +01004285void TouchInputMapper::clearStylusDataPendingFlags() {
4286 mExternalStylusDataPending = false;
4287 mExternalStylusFusionTimeout = LLONG_MAX;
4288}
4289
Michael Wrightd02c5b62014-02-10 15:10:22 -08004290void TouchInputMapper::process(const RawEvent* rawEvent) {
4291 mCursorButtonAccumulator.process(rawEvent);
4292 mCursorScrollAccumulator.process(rawEvent);
4293 mTouchButtonAccumulator.process(rawEvent);
4294
4295 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4296 sync(rawEvent->when);
4297 }
4298}
4299
4300void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004301 const RawState* last = mRawStatesPending.isEmpty() ?
4302 &mCurrentRawState : &mRawStatesPending.top();
4303
4304 // Push a new state.
4305 mRawStatesPending.push();
4306 RawState* next = &mRawStatesPending.editTop();
4307 next->clear();
4308 next->when = when;
4309
Michael Wrightd02c5b62014-02-10 15:10:22 -08004310 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004311 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312 | mCursorButtonAccumulator.getButtonState();
4313
Michael Wright842500e2015-03-13 17:32:02 -07004314 // Sync scroll
4315 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4316 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004317 mCursorScrollAccumulator.finishSync();
4318
Michael Wright842500e2015-03-13 17:32:02 -07004319 // Sync touch
4320 syncTouch(when, next);
4321
4322 // Assign pointer ids.
4323 if (!mHavePointerIds) {
4324 assignPointerIds(last, next);
4325 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326
4327#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004328 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4329 "hovering ids 0x%08x -> 0x%08x",
4330 last->rawPointerData.pointerCount,
4331 next->rawPointerData.pointerCount,
4332 last->rawPointerData.touchingIdBits.value,
4333 next->rawPointerData.touchingIdBits.value,
4334 last->rawPointerData.hoveringIdBits.value,
4335 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004336#endif
4337
Michael Wright842500e2015-03-13 17:32:02 -07004338 processRawTouches(false /*timeout*/);
4339}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004340
Michael Wright842500e2015-03-13 17:32:02 -07004341void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4343 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004344 mCurrentRawState.clear();
4345 mRawStatesPending.clear();
4346 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004347 }
4348
Michael Wright842500e2015-03-13 17:32:02 -07004349 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4350 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4351 // touching the current state will only observe the events that have been dispatched to the
4352 // rest of the pipeline.
4353 const size_t N = mRawStatesPending.size();
4354 size_t count;
4355 for(count = 0; count < N; count++) {
4356 const RawState& next = mRawStatesPending[count];
4357
4358 // A failure to assign the stylus id means that we're waiting on stylus data
4359 // and so should defer the rest of the pipeline.
4360 if (assignExternalStylusId(next, timeout)) {
4361 break;
4362 }
4363
4364 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004365 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004366 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004367 if (mCurrentRawState.when < mLastRawState.when) {
4368 mCurrentRawState.when = mLastRawState.when;
4369 }
Michael Wright842500e2015-03-13 17:32:02 -07004370 cookAndDispatch(mCurrentRawState.when);
4371 }
4372 if (count != 0) {
4373 mRawStatesPending.removeItemsAt(0, count);
4374 }
4375
Michael Wright842500e2015-03-13 17:32:02 -07004376 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004377 if (timeout) {
4378 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4379 clearStylusDataPendingFlags();
4380 mCurrentRawState.copyFrom(mLastRawState);
4381#if DEBUG_STYLUS_FUSION
4382 ALOGD("Timeout expired, synthesizing event with new stylus data");
4383#endif
4384 cookAndDispatch(when);
4385 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4386 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4387 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4388 }
Michael Wright842500e2015-03-13 17:32:02 -07004389 }
4390}
4391
4392void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4393 // Always start with a clean state.
4394 mCurrentCookedState.clear();
4395
4396 // Apply stylus buttons to current raw state.
4397 applyExternalStylusButtonState(when);
4398
4399 // Handle policy on initial down or hover events.
4400 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4401 && mCurrentRawState.rawPointerData.pointerCount != 0;
4402
4403 uint32_t policyFlags = 0;
4404 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4405 if (initialDown || buttonsPressed) {
4406 // If this is a touch screen, hide the pointer on an initial down.
4407 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4408 getContext()->fadePointer();
4409 }
4410
4411 if (mParameters.wake) {
4412 policyFlags |= POLICY_FLAG_WAKE;
4413 }
4414 }
4415
4416 // Consume raw off-screen touches before cooking pointer data.
4417 // If touches are consumed, subsequent code will not receive any pointer data.
4418 if (consumeRawTouches(when, policyFlags)) {
4419 mCurrentRawState.rawPointerData.clear();
4420 }
4421
4422 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4423 // with cooked pointer data that has the same ids and indices as the raw data.
4424 // The following code can use either the raw or cooked data, as needed.
4425 cookPointerData();
4426
4427 // Apply stylus pressure to current cooked state.
4428 applyExternalStylusTouchState(when);
4429
4430 // Synthesize key down from raw buttons if needed.
4431 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004432 mViewport.displayId, policyFlags,
4433 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004434
4435 // Dispatch the touches either directly or by translation through a pointer on screen.
4436 if (mDeviceMode == DEVICE_MODE_POINTER) {
4437 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4438 !idBits.isEmpty(); ) {
4439 uint32_t id = idBits.clearFirstMarkedBit();
4440 const RawPointerData::Pointer& pointer =
4441 mCurrentRawState.rawPointerData.pointerForId(id);
4442 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4443 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4444 mCurrentCookedState.stylusIdBits.markBit(id);
4445 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4446 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4447 mCurrentCookedState.fingerIdBits.markBit(id);
4448 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4449 mCurrentCookedState.mouseIdBits.markBit(id);
4450 }
4451 }
4452 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4453 !idBits.isEmpty(); ) {
4454 uint32_t id = idBits.clearFirstMarkedBit();
4455 const RawPointerData::Pointer& pointer =
4456 mCurrentRawState.rawPointerData.pointerForId(id);
4457 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4458 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4459 mCurrentCookedState.stylusIdBits.markBit(id);
4460 }
4461 }
4462
4463 // Stylus takes precedence over all tools, then mouse, then finger.
4464 PointerUsage pointerUsage = mPointerUsage;
4465 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4466 mCurrentCookedState.mouseIdBits.clear();
4467 mCurrentCookedState.fingerIdBits.clear();
4468 pointerUsage = POINTER_USAGE_STYLUS;
4469 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4470 mCurrentCookedState.fingerIdBits.clear();
4471 pointerUsage = POINTER_USAGE_MOUSE;
4472 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4473 isPointerDown(mCurrentRawState.buttonState)) {
4474 pointerUsage = POINTER_USAGE_GESTURES;
4475 }
4476
4477 dispatchPointerUsage(when, policyFlags, pointerUsage);
4478 } else {
4479 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004480 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004481 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4482 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4483
4484 mPointerController->setButtonState(mCurrentRawState.buttonState);
4485 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4486 mCurrentCookedState.cookedPointerData.idToIndex,
4487 mCurrentCookedState.cookedPointerData.touchingIdBits);
4488 }
4489
Michael Wright8e812822015-06-22 16:18:21 +01004490 if (!mCurrentMotionAborted) {
4491 dispatchButtonRelease(when, policyFlags);
4492 dispatchHoverExit(when, policyFlags);
4493 dispatchTouches(when, policyFlags);
4494 dispatchHoverEnterAndMove(when, policyFlags);
4495 dispatchButtonPress(when, policyFlags);
4496 }
4497
4498 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4499 mCurrentMotionAborted = false;
4500 }
Michael Wright842500e2015-03-13 17:32:02 -07004501 }
4502
4503 // Synthesize key up from raw buttons if needed.
4504 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004505 mViewport.displayId, policyFlags,
4506 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004507
4508 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004509 mCurrentRawState.rawVScroll = 0;
4510 mCurrentRawState.rawHScroll = 0;
4511
4512 // Copy current touch to last touch in preparation for the next cycle.
4513 mLastRawState.copyFrom(mCurrentRawState);
4514 mLastCookedState.copyFrom(mCurrentCookedState);
4515}
4516
4517void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004518 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004519 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4520 }
4521}
4522
4523void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004524 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4525 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004526
Michael Wright53dca3a2015-04-23 17:39:53 +01004527 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4528 float pressure = mExternalStylusState.pressure;
4529 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4530 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4531 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4532 }
4533 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4534 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4535
4536 PointerProperties& properties =
4537 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004538 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4539 properties.toolType = mExternalStylusState.toolType;
4540 }
4541 }
4542}
4543
4544bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4545 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4546 return false;
4547 }
4548
4549 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4550 && state.rawPointerData.pointerCount != 0;
4551 if (initialDown) {
4552 if (mExternalStylusState.pressure != 0.0f) {
4553#if DEBUG_STYLUS_FUSION
4554 ALOGD("Have both stylus and touch data, beginning fusion");
4555#endif
4556 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4557 } else if (timeout) {
4558#if DEBUG_STYLUS_FUSION
4559 ALOGD("Timeout expired, assuming touch is not a stylus.");
4560#endif
4561 resetExternalStylus();
4562 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004563 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4564 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004565 }
4566#if DEBUG_STYLUS_FUSION
4567 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004568 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004569#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004570 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004571 return true;
4572 }
4573 }
4574
4575 // Check if the stylus pointer has gone up.
4576 if (mExternalStylusId != -1 &&
4577 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4578#if DEBUG_STYLUS_FUSION
4579 ALOGD("Stylus pointer is going up");
4580#endif
4581 mExternalStylusId = -1;
4582 }
4583
4584 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585}
4586
4587void TouchInputMapper::timeoutExpired(nsecs_t when) {
4588 if (mDeviceMode == DEVICE_MODE_POINTER) {
4589 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4590 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4591 }
Michael Wright842500e2015-03-13 17:32:02 -07004592 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004593 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004594 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004595 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4596 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004597 }
4598 }
4599}
4600
4601void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004602 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004603 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004604 // We're either in the middle of a fused stream of data or we're waiting on data before
4605 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4606 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004607 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004608 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004609 }
4610}
4611
4612bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4613 // Check for release of a virtual key.
4614 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004615 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004616 // Pointer went up while virtual key was down.
4617 mCurrentVirtualKey.down = false;
4618 if (!mCurrentVirtualKey.ignored) {
4619#if DEBUG_VIRTUAL_KEYS
4620 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4621 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4622#endif
4623 dispatchVirtualKey(when, policyFlags,
4624 AKEY_EVENT_ACTION_UP,
4625 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4626 }
4627 return true;
4628 }
4629
Michael Wright842500e2015-03-13 17:32:02 -07004630 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4631 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4632 const RawPointerData::Pointer& pointer =
4633 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4635 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4636 // Pointer is still within the space of the virtual key.
4637 return true;
4638 }
4639 }
4640
4641 // Pointer left virtual key area or another pointer also went down.
4642 // Send key cancellation but do not consume the touch yet.
4643 // This is useful when the user swipes through from the virtual key area
4644 // into the main display surface.
4645 mCurrentVirtualKey.down = false;
4646 if (!mCurrentVirtualKey.ignored) {
4647#if DEBUG_VIRTUAL_KEYS
4648 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4649 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4650#endif
4651 dispatchVirtualKey(when, policyFlags,
4652 AKEY_EVENT_ACTION_UP,
4653 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4654 | AKEY_EVENT_FLAG_CANCELED);
4655 }
4656 }
4657
Michael Wright842500e2015-03-13 17:32:02 -07004658 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4659 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004660 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004661 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4662 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004663 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4664 // If exactly one pointer went down, check for virtual key hit.
4665 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004666 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004667 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4668 if (virtualKey) {
4669 mCurrentVirtualKey.down = true;
4670 mCurrentVirtualKey.downTime = when;
4671 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4672 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4673 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4674 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4675
4676 if (!mCurrentVirtualKey.ignored) {
4677#if DEBUG_VIRTUAL_KEYS
4678 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4679 mCurrentVirtualKey.keyCode,
4680 mCurrentVirtualKey.scanCode);
4681#endif
4682 dispatchVirtualKey(when, policyFlags,
4683 AKEY_EVENT_ACTION_DOWN,
4684 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4685 }
4686 }
4687 }
4688 return true;
4689 }
4690 }
4691
4692 // Disable all virtual key touches that happen within a short time interval of the
4693 // most recent touch within the screen area. The idea is to filter out stray
4694 // virtual key presses when interacting with the touch screen.
4695 //
4696 // Problems we're trying to solve:
4697 //
4698 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4699 // virtual key area that is implemented by a separate touch panel and accidentally
4700 // triggers a virtual key.
4701 //
4702 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4703 // area and accidentally triggers a virtual key. This often happens when virtual keys
4704 // are layed out below the screen near to where the on screen keyboard's space bar
4705 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004706 if (mConfig.virtualKeyQuietTime > 0 &&
4707 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004708 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4709 }
4710 return false;
4711}
4712
4713void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4714 int32_t keyEventAction, int32_t keyEventFlags) {
4715 int32_t keyCode = mCurrentVirtualKey.keyCode;
4716 int32_t scanCode = mCurrentVirtualKey.scanCode;
4717 nsecs_t downTime = mCurrentVirtualKey.downTime;
4718 int32_t metaState = mContext->getGlobalMetaState();
4719 policyFlags |= POLICY_FLAG_VIRTUAL;
4720
Prabir Pradhan42611e02018-11-27 14:04:02 -08004721 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4722 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004723 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724 getListener()->notifyKey(&args);
4725}
4726
Michael Wright8e812822015-06-22 16:18:21 +01004727void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4728 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4729 if (!currentIdBits.isEmpty()) {
4730 int32_t metaState = getContext()->getGlobalMetaState();
4731 int32_t buttonState = mCurrentCookedState.buttonState;
4732 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4733 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004734 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004735 mCurrentCookedState.cookedPointerData.pointerProperties,
4736 mCurrentCookedState.cookedPointerData.pointerCoords,
4737 mCurrentCookedState.cookedPointerData.idToIndex,
4738 currentIdBits, -1,
4739 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4740 mCurrentMotionAborted = true;
4741 }
4742}
4743
Michael Wrightd02c5b62014-02-10 15:10:22 -08004744void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004745 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4746 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004747 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004748 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004749
4750 if (currentIdBits == lastIdBits) {
4751 if (!currentIdBits.isEmpty()) {
4752 // No pointer id changes so this is a move event.
4753 // The listener takes care of batching moves so we don't have to deal with that here.
4754 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004755 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004757 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004758 mCurrentCookedState.cookedPointerData.pointerProperties,
4759 mCurrentCookedState.cookedPointerData.pointerCoords,
4760 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004761 currentIdBits, -1,
4762 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4763 }
4764 } else {
4765 // There may be pointers going up and pointers going down and pointers moving
4766 // all at the same time.
4767 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4768 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4769 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4770 BitSet32 dispatchedIdBits(lastIdBits.value);
4771
4772 // Update last coordinates of pointers that have moved so that we observe the new
4773 // pointer positions at the same time as other pointers that have just gone up.
4774 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004775 mCurrentCookedState.cookedPointerData.pointerProperties,
4776 mCurrentCookedState.cookedPointerData.pointerCoords,
4777 mCurrentCookedState.cookedPointerData.idToIndex,
4778 mLastCookedState.cookedPointerData.pointerProperties,
4779 mLastCookedState.cookedPointerData.pointerCoords,
4780 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004781 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004782 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004783 moveNeeded = true;
4784 }
4785
4786 // Dispatch pointer up events.
4787 while (!upIdBits.isEmpty()) {
4788 uint32_t upId = upIdBits.clearFirstMarkedBit();
4789
4790 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004791 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004792 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004793 mLastCookedState.cookedPointerData.pointerProperties,
4794 mLastCookedState.cookedPointerData.pointerCoords,
4795 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004796 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004797 dispatchedIdBits.clearBit(upId);
4798 }
4799
4800 // Dispatch move events if any of the remaining pointers moved from their old locations.
4801 // Although applications receive new locations as part of individual pointer up
4802 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004803 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4805 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004806 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004807 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004808 mCurrentCookedState.cookedPointerData.pointerProperties,
4809 mCurrentCookedState.cookedPointerData.pointerCoords,
4810 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004811 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004812 }
4813
4814 // Dispatch pointer down events using the new pointer locations.
4815 while (!downIdBits.isEmpty()) {
4816 uint32_t downId = downIdBits.clearFirstMarkedBit();
4817 dispatchedIdBits.markBit(downId);
4818
4819 if (dispatchedIdBits.count() == 1) {
4820 // First pointer is going down. Set down time.
4821 mDownTime = when;
4822 }
4823
4824 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004825 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004826 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004827 mCurrentCookedState.cookedPointerData.pointerProperties,
4828 mCurrentCookedState.cookedPointerData.pointerCoords,
4829 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004830 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832 }
4833}
4834
4835void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4836 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004837 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4838 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 int32_t metaState = getContext()->getGlobalMetaState();
4840 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004841 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004842 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004843 mLastCookedState.cookedPointerData.pointerProperties,
4844 mLastCookedState.cookedPointerData.pointerCoords,
4845 mLastCookedState.cookedPointerData.idToIndex,
4846 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4848 mSentHoverEnter = false;
4849 }
4850}
4851
4852void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004853 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4854 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855 int32_t metaState = getContext()->getGlobalMetaState();
4856 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004857 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004858 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004859 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004860 mCurrentCookedState.cookedPointerData.pointerProperties,
4861 mCurrentCookedState.cookedPointerData.pointerCoords,
4862 mCurrentCookedState.cookedPointerData.idToIndex,
4863 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4865 mSentHoverEnter = true;
4866 }
4867
4868 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004869 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004870 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004871 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004872 mCurrentCookedState.cookedPointerData.pointerProperties,
4873 mCurrentCookedState.cookedPointerData.pointerCoords,
4874 mCurrentCookedState.cookedPointerData.idToIndex,
4875 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004876 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4877 }
4878}
4879
Michael Wright7b159c92015-05-14 14:48:03 +01004880void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4881 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4882 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4883 const int32_t metaState = getContext()->getGlobalMetaState();
4884 int32_t buttonState = mLastCookedState.buttonState;
4885 while (!releasedButtons.isEmpty()) {
4886 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4887 buttonState &= ~actionButton;
4888 dispatchMotion(when, policyFlags, mSource,
4889 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4890 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004891 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004892 mCurrentCookedState.cookedPointerData.pointerProperties,
4893 mCurrentCookedState.cookedPointerData.pointerCoords,
4894 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4895 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4896 }
4897}
4898
4899void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4900 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4901 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4902 const int32_t metaState = getContext()->getGlobalMetaState();
4903 int32_t buttonState = mLastCookedState.buttonState;
4904 while (!pressedButtons.isEmpty()) {
4905 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4906 buttonState |= actionButton;
4907 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4908 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004909 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004910 mCurrentCookedState.cookedPointerData.pointerProperties,
4911 mCurrentCookedState.cookedPointerData.pointerCoords,
4912 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4913 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4914 }
4915}
4916
4917const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4918 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4919 return cookedPointerData.touchingIdBits;
4920 }
4921 return cookedPointerData.hoveringIdBits;
4922}
4923
Michael Wrightd02c5b62014-02-10 15:10:22 -08004924void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004925 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
Michael Wright842500e2015-03-13 17:32:02 -07004927 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004928 mCurrentCookedState.deviceTimestamp =
4929 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004930 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4931 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4932 mCurrentRawState.rawPointerData.hoveringIdBits;
4933 mCurrentCookedState.cookedPointerData.touchingIdBits =
4934 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004935
Michael Wright7b159c92015-05-14 14:48:03 +01004936 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4937 mCurrentCookedState.buttonState = 0;
4938 } else {
4939 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4940 }
4941
Michael Wrightd02c5b62014-02-10 15:10:22 -08004942 // Walk through the the active pointers and map device coordinates onto
4943 // surface coordinates and adjust for display orientation.
4944 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004945 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004946
4947 // Size
4948 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4949 switch (mCalibration.sizeCalibration) {
4950 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4951 case Calibration::SIZE_CALIBRATION_DIAMETER:
4952 case Calibration::SIZE_CALIBRATION_BOX:
4953 case Calibration::SIZE_CALIBRATION_AREA:
4954 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4955 touchMajor = in.touchMajor;
4956 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4957 toolMajor = in.toolMajor;
4958 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4959 size = mRawPointerAxes.touchMinor.valid
4960 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4961 } else if (mRawPointerAxes.touchMajor.valid) {
4962 toolMajor = touchMajor = in.touchMajor;
4963 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4964 ? in.touchMinor : in.touchMajor;
4965 size = mRawPointerAxes.touchMinor.valid
4966 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4967 } else if (mRawPointerAxes.toolMajor.valid) {
4968 touchMajor = toolMajor = in.toolMajor;
4969 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4970 ? in.toolMinor : in.toolMajor;
4971 size = mRawPointerAxes.toolMinor.valid
4972 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4973 } else {
4974 ALOG_ASSERT(false, "No touch or tool axes. "
4975 "Size calibration should have been resolved to NONE.");
4976 touchMajor = 0;
4977 touchMinor = 0;
4978 toolMajor = 0;
4979 toolMinor = 0;
4980 size = 0;
4981 }
4982
4983 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004984 uint32_t touchingCount =
4985 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004986 if (touchingCount > 1) {
4987 touchMajor /= touchingCount;
4988 touchMinor /= touchingCount;
4989 toolMajor /= touchingCount;
4990 toolMinor /= touchingCount;
4991 size /= touchingCount;
4992 }
4993 }
4994
4995 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4996 touchMajor *= mGeometricScale;
4997 touchMinor *= mGeometricScale;
4998 toolMajor *= mGeometricScale;
4999 toolMinor *= mGeometricScale;
5000 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
5001 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
5002 touchMinor = touchMajor;
5003 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
5004 toolMinor = toolMajor;
5005 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
5006 touchMinor = touchMajor;
5007 toolMinor = toolMajor;
5008 }
5009
5010 mCalibration.applySizeScaleAndBias(&touchMajor);
5011 mCalibration.applySizeScaleAndBias(&touchMinor);
5012 mCalibration.applySizeScaleAndBias(&toolMajor);
5013 mCalibration.applySizeScaleAndBias(&toolMinor);
5014 size *= mSizeScale;
5015 break;
5016 default:
5017 touchMajor = 0;
5018 touchMinor = 0;
5019 toolMajor = 0;
5020 toolMinor = 0;
5021 size = 0;
5022 break;
5023 }
5024
5025 // Pressure
5026 float pressure;
5027 switch (mCalibration.pressureCalibration) {
5028 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5029 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5030 pressure = in.pressure * mPressureScale;
5031 break;
5032 default:
5033 pressure = in.isHovering ? 0 : 1;
5034 break;
5035 }
5036
5037 // Tilt and Orientation
5038 float tilt;
5039 float orientation;
5040 if (mHaveTilt) {
5041 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5042 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5043 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5044 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5045 } else {
5046 tilt = 0;
5047
5048 switch (mCalibration.orientationCalibration) {
5049 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5050 orientation = in.orientation * mOrientationScale;
5051 break;
5052 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5053 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5054 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5055 if (c1 != 0 || c2 != 0) {
5056 orientation = atan2f(c1, c2) * 0.5f;
5057 float confidence = hypotf(c1, c2);
5058 float scale = 1.0f + confidence / 16.0f;
5059 touchMajor *= scale;
5060 touchMinor /= scale;
5061 toolMajor *= scale;
5062 toolMinor /= scale;
5063 } else {
5064 orientation = 0;
5065 }
5066 break;
5067 }
5068 default:
5069 orientation = 0;
5070 }
5071 }
5072
5073 // Distance
5074 float distance;
5075 switch (mCalibration.distanceCalibration) {
5076 case Calibration::DISTANCE_CALIBRATION_SCALED:
5077 distance = in.distance * mDistanceScale;
5078 break;
5079 default:
5080 distance = 0;
5081 }
5082
5083 // Coverage
5084 int32_t rawLeft, rawTop, rawRight, rawBottom;
5085 switch (mCalibration.coverageCalibration) {
5086 case Calibration::COVERAGE_CALIBRATION_BOX:
5087 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5088 rawRight = in.toolMinor & 0x0000ffff;
5089 rawBottom = in.toolMajor & 0x0000ffff;
5090 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5091 break;
5092 default:
5093 rawLeft = rawTop = rawRight = rawBottom = 0;
5094 break;
5095 }
5096
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005097 // Adjust X,Y coords for device calibration
5098 // TODO: Adjust coverage coords?
5099 float xTransformed = in.x, yTransformed = in.y;
5100 mAffineTransform.applyTo(xTransformed, yTransformed);
5101
5102 // Adjust X, Y, and coverage coords for surface orientation.
5103 float x, y;
5104 float left, top, right, bottom;
5105
Michael Wrightd02c5b62014-02-10 15:10:22 -08005106 switch (mSurfaceOrientation) {
5107 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005108 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5109 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005110 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5111 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5112 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5113 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5114 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005115 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5117 }
5118 break;
5119 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005120 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005121 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005122 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5123 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005124 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5125 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5126 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005127 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5129 }
5130 break;
5131 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005132 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005133 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005134 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5135 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005136 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5137 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5138 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005139 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005140 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5141 }
5142 break;
5143 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005144 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5145 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005146 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5147 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5148 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5149 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5150 break;
5151 }
5152
5153 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005154 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005155 out.clear();
5156 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5157 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5158 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5159 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5160 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5161 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5162 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5163 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5164 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5165 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5166 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5167 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5168 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5169 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5170 } else {
5171 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5172 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5173 }
5174
5175 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005176 PointerProperties& properties =
5177 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005178 uint32_t id = in.id;
5179 properties.clear();
5180 properties.id = id;
5181 properties.toolType = in.toolType;
5182
5183 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005184 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005185 }
5186}
5187
5188void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5189 PointerUsage pointerUsage) {
5190 if (pointerUsage != mPointerUsage) {
5191 abortPointerUsage(when, policyFlags);
5192 mPointerUsage = pointerUsage;
5193 }
5194
5195 switch (mPointerUsage) {
5196 case POINTER_USAGE_GESTURES:
5197 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5198 break;
5199 case POINTER_USAGE_STYLUS:
5200 dispatchPointerStylus(when, policyFlags);
5201 break;
5202 case POINTER_USAGE_MOUSE:
5203 dispatchPointerMouse(when, policyFlags);
5204 break;
5205 default:
5206 break;
5207 }
5208}
5209
5210void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5211 switch (mPointerUsage) {
5212 case POINTER_USAGE_GESTURES:
5213 abortPointerGestures(when, policyFlags);
5214 break;
5215 case POINTER_USAGE_STYLUS:
5216 abortPointerStylus(when, policyFlags);
5217 break;
5218 case POINTER_USAGE_MOUSE:
5219 abortPointerMouse(when, policyFlags);
5220 break;
5221 default:
5222 break;
5223 }
5224
5225 mPointerUsage = POINTER_USAGE_NONE;
5226}
5227
5228void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5229 bool isTimeout) {
5230 // Update current gesture coordinates.
5231 bool cancelPreviousGesture, finishPreviousGesture;
5232 bool sendEvents = preparePointerGestures(when,
5233 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5234 if (!sendEvents) {
5235 return;
5236 }
5237 if (finishPreviousGesture) {
5238 cancelPreviousGesture = false;
5239 }
5240
5241 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005242 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5243 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005244 if (finishPreviousGesture || cancelPreviousGesture) {
5245 mPointerController->clearSpots();
5246 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005247
5248 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5249 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5250 mPointerGesture.currentGestureIdToIndex,
5251 mPointerGesture.currentGestureIdBits);
5252 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005253 } else {
5254 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5255 }
5256
5257 // Show or hide the pointer if needed.
5258 switch (mPointerGesture.currentGestureMode) {
5259 case PointerGesture::NEUTRAL:
5260 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005261 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5262 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005263 // Remind the user of where the pointer is after finishing a gesture with spots.
5264 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5265 }
5266 break;
5267 case PointerGesture::TAP:
5268 case PointerGesture::TAP_DRAG:
5269 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5270 case PointerGesture::HOVER:
5271 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005272 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 // Unfade the pointer when the current gesture manipulates the
5274 // area directly under the pointer.
5275 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5276 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005277 case PointerGesture::FREEFORM:
5278 // Fade the pointer when the current gesture manipulates a different
5279 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005280 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005281 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5282 } else {
5283 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5284 }
5285 break;
5286 }
5287
5288 // Send events!
5289 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005290 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005291
5292 // Update last coordinates of pointers that have moved so that we observe the new
5293 // pointer positions at the same time as other pointers that have just gone up.
5294 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5295 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5296 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5297 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5298 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5299 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5300 bool moveNeeded = false;
5301 if (down && !cancelPreviousGesture && !finishPreviousGesture
5302 && !mPointerGesture.lastGestureIdBits.isEmpty()
5303 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5304 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5305 & mPointerGesture.lastGestureIdBits.value);
5306 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5307 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5308 mPointerGesture.lastGestureProperties,
5309 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5310 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005311 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005312 moveNeeded = true;
5313 }
5314 }
5315
5316 // Send motion events for all pointers that went up or were canceled.
5317 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5318 if (!dispatchedGestureIdBits.isEmpty()) {
5319 if (cancelPreviousGesture) {
5320 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005321 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005322 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005323 mPointerGesture.lastGestureProperties,
5324 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005325 dispatchedGestureIdBits, -1, 0,
5326 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005327
5328 dispatchedGestureIdBits.clear();
5329 } else {
5330 BitSet32 upGestureIdBits;
5331 if (finishPreviousGesture) {
5332 upGestureIdBits = dispatchedGestureIdBits;
5333 } else {
5334 upGestureIdBits.value = dispatchedGestureIdBits.value
5335 & ~mPointerGesture.currentGestureIdBits.value;
5336 }
5337 while (!upGestureIdBits.isEmpty()) {
5338 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5339
5340 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005341 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005342 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005343 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005344 mPointerGesture.lastGestureProperties,
5345 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5346 dispatchedGestureIdBits, id,
5347 0, 0, mPointerGesture.downTime);
5348
5349 dispatchedGestureIdBits.clearBit(id);
5350 }
5351 }
5352 }
5353
5354 // Send motion events for all pointers that moved.
5355 if (moveNeeded) {
5356 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005357 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005358 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005359 mPointerGesture.currentGestureProperties,
5360 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5361 dispatchedGestureIdBits, -1,
5362 0, 0, mPointerGesture.downTime);
5363 }
5364
5365 // Send motion events for all pointers that went down.
5366 if (down) {
5367 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5368 & ~dispatchedGestureIdBits.value);
5369 while (!downGestureIdBits.isEmpty()) {
5370 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5371 dispatchedGestureIdBits.markBit(id);
5372
5373 if (dispatchedGestureIdBits.count() == 1) {
5374 mPointerGesture.downTime = when;
5375 }
5376
5377 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005378 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005379 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005380 mPointerGesture.currentGestureProperties,
5381 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5382 dispatchedGestureIdBits, id,
5383 0, 0, mPointerGesture.downTime);
5384 }
5385 }
5386
5387 // Send motion events for hover.
5388 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5389 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005390 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005391 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392 mPointerGesture.currentGestureProperties,
5393 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5394 mPointerGesture.currentGestureIdBits, -1,
5395 0, 0, mPointerGesture.downTime);
5396 } else if (dispatchedGestureIdBits.isEmpty()
5397 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5398 // Synthesize a hover move event after all pointers go up to indicate that
5399 // the pointer is hovering again even if the user is not currently touching
5400 // the touch pad. This ensures that a view will receive a fresh hover enter
5401 // event after a tap.
5402 float x, y;
5403 mPointerController->getPosition(&x, &y);
5404
5405 PointerProperties pointerProperties;
5406 pointerProperties.clear();
5407 pointerProperties.id = 0;
5408 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5409
5410 PointerCoords pointerCoords;
5411 pointerCoords.clear();
5412 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5413 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5414
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005415 const int32_t displayId = mPointerController->getDisplayId();
Dan Harmsaca28402018-12-17 13:55:20 -08005416 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005417 mSource, displayId, policyFlags,
Dan Harmsaca28402018-12-17 13:55:20 -08005418 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08005419 metaState, buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005420 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005421 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005422 getListener()->notifyMotion(&args);
5423 }
5424
5425 // Update state.
5426 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5427 if (!down) {
5428 mPointerGesture.lastGestureIdBits.clear();
5429 } else {
5430 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5431 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5432 uint32_t id = idBits.clearFirstMarkedBit();
5433 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5434 mPointerGesture.lastGestureProperties[index].copyFrom(
5435 mPointerGesture.currentGestureProperties[index]);
5436 mPointerGesture.lastGestureCoords[index].copyFrom(
5437 mPointerGesture.currentGestureCoords[index]);
5438 mPointerGesture.lastGestureIdToIndex[id] = index;
5439 }
5440 }
5441}
5442
5443void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5444 // Cancel previously dispatches pointers.
5445 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5446 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005447 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005449 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005450 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005451 mPointerGesture.lastGestureProperties,
5452 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5453 mPointerGesture.lastGestureIdBits, -1,
5454 0, 0, mPointerGesture.downTime);
5455 }
5456
5457 // Reset the current pointer gesture.
5458 mPointerGesture.reset();
5459 mPointerVelocityControl.reset();
5460
5461 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005462 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005463 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5464 mPointerController->clearSpots();
5465 }
5466}
5467
5468bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5469 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5470 *outCancelPreviousGesture = false;
5471 *outFinishPreviousGesture = false;
5472
5473 // Handle TAP timeout.
5474 if (isTimeout) {
5475#if DEBUG_GESTURES
5476 ALOGD("Gestures: Processing timeout");
5477#endif
5478
5479 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5480 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5481 // The tap/drag timeout has not yet expired.
5482 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5483 + mConfig.pointerGestureTapDragInterval);
5484 } else {
5485 // The tap is finished.
5486#if DEBUG_GESTURES
5487 ALOGD("Gestures: TAP finished");
5488#endif
5489 *outFinishPreviousGesture = true;
5490
5491 mPointerGesture.activeGestureId = -1;
5492 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5493 mPointerGesture.currentGestureIdBits.clear();
5494
5495 mPointerVelocityControl.reset();
5496 return true;
5497 }
5498 }
5499
5500 // We did not handle this timeout.
5501 return false;
5502 }
5503
Michael Wright842500e2015-03-13 17:32:02 -07005504 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5505 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506
5507 // Update the velocity tracker.
5508 {
5509 VelocityTracker::Position positions[MAX_POINTERS];
5510 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005511 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005513 const RawPointerData::Pointer& pointer =
5514 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005515 positions[count].x = pointer.x * mPointerXMovementScale;
5516 positions[count].y = pointer.y * mPointerYMovementScale;
5517 }
5518 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005519 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 }
5521
5522 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5523 // to NEUTRAL, then we should not generate tap event.
5524 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5525 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5526 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5527 mPointerGesture.resetTap();
5528 }
5529
5530 // Pick a new active touch id if needed.
5531 // Choose an arbitrary pointer that just went down, if there is one.
5532 // Otherwise choose an arbitrary remaining pointer.
5533 // This guarantees we always have an active touch id when there is at least one pointer.
5534 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005535 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5536 int32_t activeTouchId = lastActiveTouchId;
5537 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005538 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005539 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005540 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005541 mPointerGesture.firstTouchTime = when;
5542 }
Michael Wright842500e2015-03-13 17:32:02 -07005543 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005544 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005545 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005546 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005547 } else {
5548 activeTouchId = mPointerGesture.activeTouchId = -1;
5549 }
5550 }
5551
5552 // Determine whether we are in quiet time.
5553 bool isQuietTime = false;
5554 if (activeTouchId < 0) {
5555 mPointerGesture.resetQuietTime();
5556 } else {
5557 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5558 if (!isQuietTime) {
5559 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5560 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5561 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5562 && currentFingerCount < 2) {
5563 // Enter quiet time when exiting swipe or freeform state.
5564 // This is to prevent accidentally entering the hover state and flinging the
5565 // pointer when finishing a swipe and there is still one pointer left onscreen.
5566 isQuietTime = true;
5567 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5568 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005569 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005570 // Enter quiet time when releasing the button and there are still two or more
5571 // fingers down. This may indicate that one finger was used to press the button
5572 // but it has not gone up yet.
5573 isQuietTime = true;
5574 }
5575 if (isQuietTime) {
5576 mPointerGesture.quietTime = when;
5577 }
5578 }
5579 }
5580
5581 // Switch states based on button and pointer state.
5582 if (isQuietTime) {
5583 // Case 1: Quiet time. (QUIET)
5584#if DEBUG_GESTURES
5585 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5586 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5587#endif
5588 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5589 *outFinishPreviousGesture = true;
5590 }
5591
5592 mPointerGesture.activeGestureId = -1;
5593 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5594 mPointerGesture.currentGestureIdBits.clear();
5595
5596 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005597 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005598 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5599 // The pointer follows the active touch point.
5600 // Emit DOWN, MOVE, UP events at the pointer location.
5601 //
5602 // Only the active touch matters; other fingers are ignored. This policy helps
5603 // to handle the case where the user places a second finger on the touch pad
5604 // to apply the necessary force to depress an integrated button below the surface.
5605 // We don't want the second finger to be delivered to applications.
5606 //
5607 // For this to work well, we need to make sure to track the pointer that is really
5608 // active. If the user first puts one finger down to click then adds another
5609 // finger to drag then the active pointer should switch to the finger that is
5610 // being dragged.
5611#if DEBUG_GESTURES
5612 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5613 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5614#endif
5615 // Reset state when just starting.
5616 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5617 *outFinishPreviousGesture = true;
5618 mPointerGesture.activeGestureId = 0;
5619 }
5620
5621 // Switch pointers if needed.
5622 // Find the fastest pointer and follow it.
5623 if (activeTouchId >= 0 && currentFingerCount > 1) {
5624 int32_t bestId = -1;
5625 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005626 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627 uint32_t id = idBits.clearFirstMarkedBit();
5628 float vx, vy;
5629 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5630 float speed = hypotf(vx, vy);
5631 if (speed > bestSpeed) {
5632 bestId = id;
5633 bestSpeed = speed;
5634 }
5635 }
5636 }
5637 if (bestId >= 0 && bestId != activeTouchId) {
5638 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639#if DEBUG_GESTURES
5640 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5641 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5642#endif
5643 }
5644 }
5645
Jun Mukaifa1706a2015-12-03 01:14:46 -08005646 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005647 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005648 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005649 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005650 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005651 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005652 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5653 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005654
5655 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5656 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5657
5658 // Move the pointer using a relative motion.
5659 // When using spots, the click will occur at the position of the anchor
5660 // spot and all other spots will move there.
5661 mPointerController->move(deltaX, deltaY);
5662 } else {
5663 mPointerVelocityControl.reset();
5664 }
5665
5666 float x, y;
5667 mPointerController->getPosition(&x, &y);
5668
5669 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5670 mPointerGesture.currentGestureIdBits.clear();
5671 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5672 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5673 mPointerGesture.currentGestureProperties[0].clear();
5674 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5675 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5676 mPointerGesture.currentGestureCoords[0].clear();
5677 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5678 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5679 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5680 } else if (currentFingerCount == 0) {
5681 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5682 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5683 *outFinishPreviousGesture = true;
5684 }
5685
5686 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5687 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5688 bool tapped = false;
5689 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5690 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5691 && lastFingerCount == 1) {
5692 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5693 float x, y;
5694 mPointerController->getPosition(&x, &y);
5695 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5696 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5697#if DEBUG_GESTURES
5698 ALOGD("Gestures: TAP");
5699#endif
5700
5701 mPointerGesture.tapUpTime = when;
5702 getContext()->requestTimeoutAtTime(when
5703 + mConfig.pointerGestureTapDragInterval);
5704
5705 mPointerGesture.activeGestureId = 0;
5706 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5707 mPointerGesture.currentGestureIdBits.clear();
5708 mPointerGesture.currentGestureIdBits.markBit(
5709 mPointerGesture.activeGestureId);
5710 mPointerGesture.currentGestureIdToIndex[
5711 mPointerGesture.activeGestureId] = 0;
5712 mPointerGesture.currentGestureProperties[0].clear();
5713 mPointerGesture.currentGestureProperties[0].id =
5714 mPointerGesture.activeGestureId;
5715 mPointerGesture.currentGestureProperties[0].toolType =
5716 AMOTION_EVENT_TOOL_TYPE_FINGER;
5717 mPointerGesture.currentGestureCoords[0].clear();
5718 mPointerGesture.currentGestureCoords[0].setAxisValue(
5719 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5720 mPointerGesture.currentGestureCoords[0].setAxisValue(
5721 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5722 mPointerGesture.currentGestureCoords[0].setAxisValue(
5723 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5724
5725 tapped = true;
5726 } else {
5727#if DEBUG_GESTURES
5728 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5729 x - mPointerGesture.tapX,
5730 y - mPointerGesture.tapY);
5731#endif
5732 }
5733 } else {
5734#if DEBUG_GESTURES
5735 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5736 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5737 (when - mPointerGesture.tapDownTime) * 0.000001f);
5738 } else {
5739 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5740 }
5741#endif
5742 }
5743 }
5744
5745 mPointerVelocityControl.reset();
5746
5747 if (!tapped) {
5748#if DEBUG_GESTURES
5749 ALOGD("Gestures: NEUTRAL");
5750#endif
5751 mPointerGesture.activeGestureId = -1;
5752 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5753 mPointerGesture.currentGestureIdBits.clear();
5754 }
5755 } else if (currentFingerCount == 1) {
5756 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5757 // The pointer follows the active touch point.
5758 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5759 // When in TAP_DRAG, emit MOVE events at the pointer location.
5760 ALOG_ASSERT(activeTouchId >= 0);
5761
5762 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5763 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5764 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5765 float x, y;
5766 mPointerController->getPosition(&x, &y);
5767 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5768 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5769 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5770 } else {
5771#if DEBUG_GESTURES
5772 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5773 x - mPointerGesture.tapX,
5774 y - mPointerGesture.tapY);
5775#endif
5776 }
5777 } else {
5778#if DEBUG_GESTURES
5779 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5780 (when - mPointerGesture.tapUpTime) * 0.000001f);
5781#endif
5782 }
5783 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5784 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5785 }
5786
Jun Mukaifa1706a2015-12-03 01:14:46 -08005787 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005788 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005789 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005790 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005791 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005792 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005793 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5794 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005795
5796 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5797 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5798
5799 // Move the pointer using a relative motion.
5800 // When using spots, the hover or drag will occur at the position of the anchor spot.
5801 mPointerController->move(deltaX, deltaY);
5802 } else {
5803 mPointerVelocityControl.reset();
5804 }
5805
5806 bool down;
5807 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5808#if DEBUG_GESTURES
5809 ALOGD("Gestures: TAP_DRAG");
5810#endif
5811 down = true;
5812 } else {
5813#if DEBUG_GESTURES
5814 ALOGD("Gestures: HOVER");
5815#endif
5816 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5817 *outFinishPreviousGesture = true;
5818 }
5819 mPointerGesture.activeGestureId = 0;
5820 down = false;
5821 }
5822
5823 float x, y;
5824 mPointerController->getPosition(&x, &y);
5825
5826 mPointerGesture.currentGestureIdBits.clear();
5827 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5828 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5829 mPointerGesture.currentGestureProperties[0].clear();
5830 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5831 mPointerGesture.currentGestureProperties[0].toolType =
5832 AMOTION_EVENT_TOOL_TYPE_FINGER;
5833 mPointerGesture.currentGestureCoords[0].clear();
5834 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5835 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5836 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5837 down ? 1.0f : 0.0f);
5838
5839 if (lastFingerCount == 0 && currentFingerCount != 0) {
5840 mPointerGesture.resetTap();
5841 mPointerGesture.tapDownTime = when;
5842 mPointerGesture.tapX = x;
5843 mPointerGesture.tapY = y;
5844 }
5845 } else {
5846 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5847 // We need to provide feedback for each finger that goes down so we cannot wait
5848 // for the fingers to move before deciding what to do.
5849 //
5850 // The ambiguous case is deciding what to do when there are two fingers down but they
5851 // have not moved enough to determine whether they are part of a drag or part of a
5852 // freeform gesture, or just a press or long-press at the pointer location.
5853 //
5854 // When there are two fingers we start with the PRESS hypothesis and we generate a
5855 // down at the pointer location.
5856 //
5857 // When the two fingers move enough or when additional fingers are added, we make
5858 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5859 ALOG_ASSERT(activeTouchId >= 0);
5860
5861 bool settled = when >= mPointerGesture.firstTouchTime
5862 + mConfig.pointerGestureMultitouchSettleInterval;
5863 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5864 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5865 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5866 *outFinishPreviousGesture = true;
5867 } else if (!settled && currentFingerCount > lastFingerCount) {
5868 // Additional pointers have gone down but not yet settled.
5869 // Reset the gesture.
5870#if DEBUG_GESTURES
5871 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5872 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5873 + mConfig.pointerGestureMultitouchSettleInterval - when)
5874 * 0.000001f);
5875#endif
5876 *outCancelPreviousGesture = true;
5877 } else {
5878 // Continue previous gesture.
5879 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5880 }
5881
5882 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5883 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5884 mPointerGesture.activeGestureId = 0;
5885 mPointerGesture.referenceIdBits.clear();
5886 mPointerVelocityControl.reset();
5887
5888 // Use the centroid and pointer location as the reference points for the gesture.
5889#if DEBUG_GESTURES
5890 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5891 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5892 + mConfig.pointerGestureMultitouchSettleInterval - when)
5893 * 0.000001f);
5894#endif
Michael Wright842500e2015-03-13 17:32:02 -07005895 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005896 &mPointerGesture.referenceTouchX,
5897 &mPointerGesture.referenceTouchY);
5898 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5899 &mPointerGesture.referenceGestureY);
5900 }
5901
5902 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005903 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005904 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5905 uint32_t id = idBits.clearFirstMarkedBit();
5906 mPointerGesture.referenceDeltas[id].dx = 0;
5907 mPointerGesture.referenceDeltas[id].dy = 0;
5908 }
Michael Wright842500e2015-03-13 17:32:02 -07005909 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005910
5911 // Add delta for all fingers and calculate a common movement delta.
5912 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005913 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5914 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005915 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5916 bool first = (idBits == commonIdBits);
5917 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005918 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5919 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5921 delta.dx += cpd.x - lpd.x;
5922 delta.dy += cpd.y - lpd.y;
5923
5924 if (first) {
5925 commonDeltaX = delta.dx;
5926 commonDeltaY = delta.dy;
5927 } else {
5928 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5929 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5930 }
5931 }
5932
5933 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5934 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5935 float dist[MAX_POINTER_ID + 1];
5936 int32_t distOverThreshold = 0;
5937 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5938 uint32_t id = idBits.clearFirstMarkedBit();
5939 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5940 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5941 delta.dy * mPointerYZoomScale);
5942 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5943 distOverThreshold += 1;
5944 }
5945 }
5946
5947 // Only transition when at least two pointers have moved further than
5948 // the minimum distance threshold.
5949 if (distOverThreshold >= 2) {
5950 if (currentFingerCount > 2) {
5951 // There are more than two pointers, switch to FREEFORM.
5952#if DEBUG_GESTURES
5953 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5954 currentFingerCount);
5955#endif
5956 *outCancelPreviousGesture = true;
5957 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5958 } else {
5959 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005960 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005961 uint32_t id1 = idBits.clearFirstMarkedBit();
5962 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005963 const RawPointerData::Pointer& p1 =
5964 mCurrentRawState.rawPointerData.pointerForId(id1);
5965 const RawPointerData::Pointer& p2 =
5966 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005967 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5968 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5969 // There are two pointers but they are too far apart for a SWIPE,
5970 // switch to FREEFORM.
5971#if DEBUG_GESTURES
5972 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5973 mutualDistance, mPointerGestureMaxSwipeWidth);
5974#endif
5975 *outCancelPreviousGesture = true;
5976 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5977 } else {
5978 // There are two pointers. Wait for both pointers to start moving
5979 // before deciding whether this is a SWIPE or FREEFORM gesture.
5980 float dist1 = dist[id1];
5981 float dist2 = dist[id2];
5982 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5983 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5984 // Calculate the dot product of the displacement vectors.
5985 // When the vectors are oriented in approximately the same direction,
5986 // the angle betweeen them is near zero and the cosine of the angle
5987 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5988 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5989 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5990 float dx1 = delta1.dx * mPointerXZoomScale;
5991 float dy1 = delta1.dy * mPointerYZoomScale;
5992 float dx2 = delta2.dx * mPointerXZoomScale;
5993 float dy2 = delta2.dy * mPointerYZoomScale;
5994 float dot = dx1 * dx2 + dy1 * dy2;
5995 float cosine = dot / (dist1 * dist2); // denominator always > 0
5996 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5997 // Pointers are moving in the same direction. Switch to SWIPE.
5998#if DEBUG_GESTURES
5999 ALOGD("Gestures: PRESS transitioned to SWIPE, "
6000 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6001 "cosine %0.3f >= %0.3f",
6002 dist1, mConfig.pointerGestureMultitouchMinDistance,
6003 dist2, mConfig.pointerGestureMultitouchMinDistance,
6004 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6005#endif
6006 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
6007 } else {
6008 // Pointers are moving in different directions. Switch to FREEFORM.
6009#if DEBUG_GESTURES
6010 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6011 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6012 "cosine %0.3f < %0.3f",
6013 dist1, mConfig.pointerGestureMultitouchMinDistance,
6014 dist2, mConfig.pointerGestureMultitouchMinDistance,
6015 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6016#endif
6017 *outCancelPreviousGesture = true;
6018 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6019 }
6020 }
6021 }
6022 }
6023 }
6024 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6025 // Switch from SWIPE to FREEFORM if additional pointers go down.
6026 // Cancel previous gesture.
6027 if (currentFingerCount > 2) {
6028#if DEBUG_GESTURES
6029 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6030 currentFingerCount);
6031#endif
6032 *outCancelPreviousGesture = true;
6033 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6034 }
6035 }
6036
6037 // Move the reference points based on the overall group motion of the fingers
6038 // except in PRESS mode while waiting for a transition to occur.
6039 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6040 && (commonDeltaX || commonDeltaY)) {
6041 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6042 uint32_t id = idBits.clearFirstMarkedBit();
6043 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6044 delta.dx = 0;
6045 delta.dy = 0;
6046 }
6047
6048 mPointerGesture.referenceTouchX += commonDeltaX;
6049 mPointerGesture.referenceTouchY += commonDeltaY;
6050
6051 commonDeltaX *= mPointerXMovementScale;
6052 commonDeltaY *= mPointerYMovementScale;
6053
6054 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6055 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6056
6057 mPointerGesture.referenceGestureX += commonDeltaX;
6058 mPointerGesture.referenceGestureY += commonDeltaY;
6059 }
6060
6061 // Report gestures.
6062 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6063 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6064 // PRESS or SWIPE mode.
6065#if DEBUG_GESTURES
6066 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6067 "activeGestureId=%d, currentTouchPointerCount=%d",
6068 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6069#endif
6070 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6071
6072 mPointerGesture.currentGestureIdBits.clear();
6073 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6074 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6075 mPointerGesture.currentGestureProperties[0].clear();
6076 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6077 mPointerGesture.currentGestureProperties[0].toolType =
6078 AMOTION_EVENT_TOOL_TYPE_FINGER;
6079 mPointerGesture.currentGestureCoords[0].clear();
6080 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6081 mPointerGesture.referenceGestureX);
6082 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6083 mPointerGesture.referenceGestureY);
6084 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6085 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6086 // FREEFORM mode.
6087#if DEBUG_GESTURES
6088 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6089 "activeGestureId=%d, currentTouchPointerCount=%d",
6090 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6091#endif
6092 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6093
6094 mPointerGesture.currentGestureIdBits.clear();
6095
6096 BitSet32 mappedTouchIdBits;
6097 BitSet32 usedGestureIdBits;
6098 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6099 // Initially, assign the active gesture id to the active touch point
6100 // if there is one. No other touch id bits are mapped yet.
6101 if (!*outCancelPreviousGesture) {
6102 mappedTouchIdBits.markBit(activeTouchId);
6103 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6104 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6105 mPointerGesture.activeGestureId;
6106 } else {
6107 mPointerGesture.activeGestureId = -1;
6108 }
6109 } else {
6110 // Otherwise, assume we mapped all touches from the previous frame.
6111 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006112 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6113 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006114 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6115
6116 // Check whether we need to choose a new active gesture id because the
6117 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006118 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6119 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 !upTouchIdBits.isEmpty(); ) {
6121 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6122 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6123 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6124 mPointerGesture.activeGestureId = -1;
6125 break;
6126 }
6127 }
6128 }
6129
6130#if DEBUG_GESTURES
6131 ALOGD("Gestures: FREEFORM follow up "
6132 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6133 "activeGestureId=%d",
6134 mappedTouchIdBits.value, usedGestureIdBits.value,
6135 mPointerGesture.activeGestureId);
6136#endif
6137
Michael Wright842500e2015-03-13 17:32:02 -07006138 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006139 for (uint32_t i = 0; i < currentFingerCount; i++) {
6140 uint32_t touchId = idBits.clearFirstMarkedBit();
6141 uint32_t gestureId;
6142 if (!mappedTouchIdBits.hasBit(touchId)) {
6143 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6144 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6145#if DEBUG_GESTURES
6146 ALOGD("Gestures: FREEFORM "
6147 "new mapping for touch id %d -> gesture id %d",
6148 touchId, gestureId);
6149#endif
6150 } else {
6151 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6152#if DEBUG_GESTURES
6153 ALOGD("Gestures: FREEFORM "
6154 "existing mapping for touch id %d -> gesture id %d",
6155 touchId, gestureId);
6156#endif
6157 }
6158 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6159 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6160
6161 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006162 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006163 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6164 * mPointerXZoomScale;
6165 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6166 * mPointerYZoomScale;
6167 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6168
6169 mPointerGesture.currentGestureProperties[i].clear();
6170 mPointerGesture.currentGestureProperties[i].id = gestureId;
6171 mPointerGesture.currentGestureProperties[i].toolType =
6172 AMOTION_EVENT_TOOL_TYPE_FINGER;
6173 mPointerGesture.currentGestureCoords[i].clear();
6174 mPointerGesture.currentGestureCoords[i].setAxisValue(
6175 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6176 mPointerGesture.currentGestureCoords[i].setAxisValue(
6177 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6178 mPointerGesture.currentGestureCoords[i].setAxisValue(
6179 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6180 }
6181
6182 if (mPointerGesture.activeGestureId < 0) {
6183 mPointerGesture.activeGestureId =
6184 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6185#if DEBUG_GESTURES
6186 ALOGD("Gestures: FREEFORM new "
6187 "activeGestureId=%d", mPointerGesture.activeGestureId);
6188#endif
6189 }
6190 }
6191 }
6192
Michael Wright842500e2015-03-13 17:32:02 -07006193 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194
6195#if DEBUG_GESTURES
6196 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6197 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6198 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6199 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6200 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6201 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6202 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6203 uint32_t id = idBits.clearFirstMarkedBit();
6204 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6205 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6206 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6207 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6208 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6209 id, index, properties.toolType,
6210 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6211 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6212 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6213 }
6214 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6215 uint32_t id = idBits.clearFirstMarkedBit();
6216 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6217 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6218 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6219 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6220 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6221 id, index, properties.toolType,
6222 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6223 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6224 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6225 }
6226#endif
6227 return true;
6228}
6229
6230void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6231 mPointerSimple.currentCoords.clear();
6232 mPointerSimple.currentProperties.clear();
6233
6234 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006235 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6236 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6237 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6238 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6239 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006240 mPointerController->setPosition(x, y);
6241
Michael Wright842500e2015-03-13 17:32:02 -07006242 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006243 down = !hovering;
6244
6245 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006246 mPointerSimple.currentCoords.copyFrom(
6247 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006248 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6249 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6250 mPointerSimple.currentProperties.id = 0;
6251 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006252 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253 } else {
6254 down = false;
6255 hovering = false;
6256 }
6257
6258 dispatchPointerSimple(when, policyFlags, down, hovering);
6259}
6260
6261void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6262 abortPointerSimple(when, policyFlags);
6263}
6264
6265void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6266 mPointerSimple.currentCoords.clear();
6267 mPointerSimple.currentProperties.clear();
6268
6269 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006270 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6271 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6272 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006273 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006274 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6275 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006276 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006277 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006279 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006280 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006281 * mPointerYMovementScale;
6282
6283 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6284 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6285
6286 mPointerController->move(deltaX, deltaY);
6287 } else {
6288 mPointerVelocityControl.reset();
6289 }
6290
Michael Wright842500e2015-03-13 17:32:02 -07006291 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006292 hovering = !down;
6293
6294 float x, y;
6295 mPointerController->getPosition(&x, &y);
6296 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006297 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6299 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6300 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6301 hovering ? 0.0f : 1.0f);
6302 mPointerSimple.currentProperties.id = 0;
6303 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006304 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305 } else {
6306 mPointerVelocityControl.reset();
6307
6308 down = false;
6309 hovering = false;
6310 }
6311
6312 dispatchPointerSimple(when, policyFlags, down, hovering);
6313}
6314
6315void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6316 abortPointerSimple(when, policyFlags);
6317
6318 mPointerVelocityControl.reset();
6319}
6320
6321void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6322 bool down, bool hovering) {
6323 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006324 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006325
Yi Kong9b14ac62018-07-17 13:48:38 -07006326 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006327 if (down || hovering) {
6328 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6329 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006330 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006331 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6332 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6333 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6334 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006335 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006336 }
6337
6338 if (mPointerSimple.down && !down) {
6339 mPointerSimple.down = false;
6340
6341 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006342 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006343 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006344 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState,
6345 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Dan Harmsaca28402018-12-17 13:55:20 -08006346 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6347 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006348 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 getListener()->notifyMotion(&args);
6350 }
6351
6352 if (mPointerSimple.hovering && !hovering) {
6353 mPointerSimple.hovering = false;
6354
6355 // Send hover exit.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006356 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6357 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006358 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState,
6359 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006360 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6361 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006362 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006363 getListener()->notifyMotion(&args);
6364 }
6365
6366 if (down) {
6367 if (!mPointerSimple.down) {
6368 mPointerSimple.down = true;
6369 mPointerSimple.downTime = when;
6370
6371 // Send down.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006372 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6373 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006374 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState,
6375 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006376 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006377 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6378 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006379 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 getListener()->notifyMotion(&args);
6381 }
6382
6383 // Send move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006384 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6385 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006386 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState,
6387 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006388 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6389 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006390 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006391 getListener()->notifyMotion(&args);
6392 }
6393
6394 if (hovering) {
6395 if (!mPointerSimple.hovering) {
6396 mPointerSimple.hovering = true;
6397
6398 // Send hover enter.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006399 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6400 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006401 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006402 mCurrentRawState.buttonState, MotionClassification::NONE,
6403 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006404 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6405 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006406 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006407 getListener()->notifyMotion(&args);
6408 }
6409
6410 // Send hover move.
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006411 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6412 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006413 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006414 mCurrentRawState.buttonState, MotionClassification::NONE,
6415 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006416 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6417 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006418 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006419 getListener()->notifyMotion(&args);
6420 }
6421
Michael Wright842500e2015-03-13 17:32:02 -07006422 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6423 float vscroll = mCurrentRawState.rawVScroll;
6424 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006425 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6426 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006427
6428 // Send scroll.
6429 PointerCoords pointerCoords;
6430 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6431 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6432 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6433
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006434 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6435 mSource, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006436 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState,
6437 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006438 1, &mPointerSimple.currentProperties, &pointerCoords,
6439 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006440 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006441 getListener()->notifyMotion(&args);
6442 }
6443
6444 // Save state.
6445 if (down || hovering) {
6446 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6447 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6448 } else {
6449 mPointerSimple.reset();
6450 }
6451}
6452
6453void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6454 mPointerSimple.currentCoords.clear();
6455 mPointerSimple.currentProperties.clear();
6456
6457 dispatchPointerSimple(when, policyFlags, false, false);
6458}
6459
6460void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006461 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006462 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006463 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006464 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6465 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006466 PointerCoords pointerCoords[MAX_POINTERS];
6467 PointerProperties pointerProperties[MAX_POINTERS];
6468 uint32_t pointerCount = 0;
6469 while (!idBits.isEmpty()) {
6470 uint32_t id = idBits.clearFirstMarkedBit();
6471 uint32_t index = idToIndex[id];
6472 pointerProperties[pointerCount].copyFrom(properties[index]);
6473 pointerCoords[pointerCount].copyFrom(coords[index]);
6474
6475 if (changedId >= 0 && id == uint32_t(changedId)) {
6476 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6477 }
6478
6479 pointerCount += 1;
6480 }
6481
6482 ALOG_ASSERT(pointerCount != 0);
6483
6484 if (changedId >= 0 && pointerCount == 1) {
6485 // Replace initial down and final up action.
6486 // We can compare the action without masking off the changed pointer index
6487 // because we know the index is 0.
6488 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6489 action = AMOTION_EVENT_ACTION_DOWN;
6490 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6491 action = AMOTION_EVENT_ACTION_UP;
6492 } else {
6493 // Can't happen.
6494 ALOG_ASSERT(false);
6495 }
6496 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006497 const int32_t displayId = mPointerController != nullptr ?
6498 mPointerController->getDisplayId() : mViewport.displayId;
Dan Harmsaca28402018-12-17 13:55:20 -08006499
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006500 const int32_t deviceId = getDeviceId();
6501 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6502 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006503 source, displayId, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08006504 action, actionButton, flags, metaState, buttonState, MotionClassification::NONE,
6505 edgeFlags, deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006506 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507 getListener()->notifyMotion(&args);
6508}
6509
6510bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6511 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6512 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6513 BitSet32 idBits) const {
6514 bool changed = false;
6515 while (!idBits.isEmpty()) {
6516 uint32_t id = idBits.clearFirstMarkedBit();
6517 uint32_t inIndex = inIdToIndex[id];
6518 uint32_t outIndex = outIdToIndex[id];
6519
6520 const PointerProperties& curInProperties = inProperties[inIndex];
6521 const PointerCoords& curInCoords = inCoords[inIndex];
6522 PointerProperties& curOutProperties = outProperties[outIndex];
6523 PointerCoords& curOutCoords = outCoords[outIndex];
6524
6525 if (curInProperties != curOutProperties) {
6526 curOutProperties.copyFrom(curInProperties);
6527 changed = true;
6528 }
6529
6530 if (curInCoords != curOutCoords) {
6531 curOutCoords.copyFrom(curInCoords);
6532 changed = true;
6533 }
6534 }
6535 return changed;
6536}
6537
6538void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006539 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006540 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6541 }
6542}
6543
Jeff Brownc9aa6282015-02-11 19:03:28 -08006544void TouchInputMapper::cancelTouch(nsecs_t when) {
6545 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006546 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006547}
6548
Michael Wrightd02c5b62014-02-10 15:10:22 -08006549bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006550 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006551 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006553 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6554 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6555 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556}
6557
6558const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6559 int32_t x, int32_t y) {
6560 size_t numVirtualKeys = mVirtualKeys.size();
6561 for (size_t i = 0; i < numVirtualKeys; i++) {
6562 const VirtualKey& virtualKey = mVirtualKeys[i];
6563
6564#if DEBUG_VIRTUAL_KEYS
6565 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6566 "left=%d, top=%d, right=%d, bottom=%d",
6567 x, y,
6568 virtualKey.keyCode, virtualKey.scanCode,
6569 virtualKey.hitLeft, virtualKey.hitTop,
6570 virtualKey.hitRight, virtualKey.hitBottom);
6571#endif
6572
6573 if (virtualKey.isHit(x, y)) {
6574 return & virtualKey;
6575 }
6576 }
6577
Yi Kong9b14ac62018-07-17 13:48:38 -07006578 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006579}
6580
Michael Wright842500e2015-03-13 17:32:02 -07006581void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6582 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6583 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006584
Michael Wright842500e2015-03-13 17:32:02 -07006585 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586
6587 if (currentPointerCount == 0) {
6588 // No pointers to assign.
6589 return;
6590 }
6591
6592 if (lastPointerCount == 0) {
6593 // All pointers are new.
6594 for (uint32_t i = 0; i < currentPointerCount; i++) {
6595 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006596 current->rawPointerData.pointers[i].id = id;
6597 current->rawPointerData.idToIndex[id] = i;
6598 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006599 }
6600 return;
6601 }
6602
6603 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006604 && current->rawPointerData.pointers[0].toolType
6605 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006606 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006607 uint32_t id = last->rawPointerData.pointers[0].id;
6608 current->rawPointerData.pointers[0].id = id;
6609 current->rawPointerData.idToIndex[id] = 0;
6610 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006611 return;
6612 }
6613
6614 // General case.
6615 // We build a heap of squared euclidean distances between current and last pointers
6616 // associated with the current and last pointer indices. Then, we find the best
6617 // match (by distance) for each current pointer.
6618 // The pointers must have the same tool type but it is possible for them to
6619 // transition from hovering to touching or vice-versa while retaining the same id.
6620 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6621
6622 uint32_t heapSize = 0;
6623 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6624 currentPointerIndex++) {
6625 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6626 lastPointerIndex++) {
6627 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006628 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006629 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006630 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 if (currentPointer.toolType == lastPointer.toolType) {
6632 int64_t deltaX = currentPointer.x - lastPointer.x;
6633 int64_t deltaY = currentPointer.y - lastPointer.y;
6634
6635 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6636
6637 // Insert new element into the heap (sift up).
6638 heap[heapSize].currentPointerIndex = currentPointerIndex;
6639 heap[heapSize].lastPointerIndex = lastPointerIndex;
6640 heap[heapSize].distance = distance;
6641 heapSize += 1;
6642 }
6643 }
6644 }
6645
6646 // Heapify
6647 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6648 startIndex -= 1;
6649 for (uint32_t parentIndex = startIndex; ;) {
6650 uint32_t childIndex = parentIndex * 2 + 1;
6651 if (childIndex >= heapSize) {
6652 break;
6653 }
6654
6655 if (childIndex + 1 < heapSize
6656 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6657 childIndex += 1;
6658 }
6659
6660 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6661 break;
6662 }
6663
6664 swap(heap[parentIndex], heap[childIndex]);
6665 parentIndex = childIndex;
6666 }
6667 }
6668
6669#if DEBUG_POINTER_ASSIGNMENT
6670 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6671 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006672 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006673 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6674 heap[i].distance);
6675 }
6676#endif
6677
6678 // Pull matches out by increasing order of distance.
6679 // To avoid reassigning pointers that have already been matched, the loop keeps track
6680 // of which last and current pointers have been matched using the matchedXXXBits variables.
6681 // It also tracks the used pointer id bits.
6682 BitSet32 matchedLastBits(0);
6683 BitSet32 matchedCurrentBits(0);
6684 BitSet32 usedIdBits(0);
6685 bool first = true;
6686 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6687 while (heapSize > 0) {
6688 if (first) {
6689 // The first time through the loop, we just consume the root element of
6690 // the heap (the one with smallest distance).
6691 first = false;
6692 } else {
6693 // Previous iterations consumed the root element of the heap.
6694 // Pop root element off of the heap (sift down).
6695 heap[0] = heap[heapSize];
6696 for (uint32_t parentIndex = 0; ;) {
6697 uint32_t childIndex = parentIndex * 2 + 1;
6698 if (childIndex >= heapSize) {
6699 break;
6700 }
6701
6702 if (childIndex + 1 < heapSize
6703 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6704 childIndex += 1;
6705 }
6706
6707 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6708 break;
6709 }
6710
6711 swap(heap[parentIndex], heap[childIndex]);
6712 parentIndex = childIndex;
6713 }
6714
6715#if DEBUG_POINTER_ASSIGNMENT
6716 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6717 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006718 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006719 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6720 heap[i].distance);
6721 }
6722#endif
6723 }
6724
6725 heapSize -= 1;
6726
6727 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6728 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6729
6730 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6731 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6732
6733 matchedCurrentBits.markBit(currentPointerIndex);
6734 matchedLastBits.markBit(lastPointerIndex);
6735
Michael Wright842500e2015-03-13 17:32:02 -07006736 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6737 current->rawPointerData.pointers[currentPointerIndex].id = id;
6738 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6739 current->rawPointerData.markIdBit(id,
6740 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006741 usedIdBits.markBit(id);
6742
6743#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006744 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6745 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006746 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6747#endif
6748 break;
6749 }
6750 }
6751
6752 // Assign fresh ids to pointers that were not matched in the process.
6753 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6754 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6755 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6756
Michael Wright842500e2015-03-13 17:32:02 -07006757 current->rawPointerData.pointers[currentPointerIndex].id = id;
6758 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6759 current->rawPointerData.markIdBit(id,
6760 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006761
6762#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006763 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006764#endif
6765 }
6766}
6767
6768int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6769 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6770 return AKEY_STATE_VIRTUAL;
6771 }
6772
6773 size_t numVirtualKeys = mVirtualKeys.size();
6774 for (size_t i = 0; i < numVirtualKeys; i++) {
6775 const VirtualKey& virtualKey = mVirtualKeys[i];
6776 if (virtualKey.keyCode == keyCode) {
6777 return AKEY_STATE_UP;
6778 }
6779 }
6780
6781 return AKEY_STATE_UNKNOWN;
6782}
6783
6784int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6785 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6786 return AKEY_STATE_VIRTUAL;
6787 }
6788
6789 size_t numVirtualKeys = mVirtualKeys.size();
6790 for (size_t i = 0; i < numVirtualKeys; i++) {
6791 const VirtualKey& virtualKey = mVirtualKeys[i];
6792 if (virtualKey.scanCode == scanCode) {
6793 return AKEY_STATE_UP;
6794 }
6795 }
6796
6797 return AKEY_STATE_UNKNOWN;
6798}
6799
6800bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6801 const int32_t* keyCodes, uint8_t* outFlags) {
6802 size_t numVirtualKeys = mVirtualKeys.size();
6803 for (size_t i = 0; i < numVirtualKeys; i++) {
6804 const VirtualKey& virtualKey = mVirtualKeys[i];
6805
6806 for (size_t i = 0; i < numCodes; i++) {
6807 if (virtualKey.keyCode == keyCodes[i]) {
6808 outFlags[i] = 1;
6809 }
6810 }
6811 }
6812
6813 return true;
6814}
6815
6816
6817// --- SingleTouchInputMapper ---
6818
6819SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6820 TouchInputMapper(device) {
6821}
6822
6823SingleTouchInputMapper::~SingleTouchInputMapper() {
6824}
6825
6826void SingleTouchInputMapper::reset(nsecs_t when) {
6827 mSingleTouchMotionAccumulator.reset(getDevice());
6828
6829 TouchInputMapper::reset(when);
6830}
6831
6832void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6833 TouchInputMapper::process(rawEvent);
6834
6835 mSingleTouchMotionAccumulator.process(rawEvent);
6836}
6837
Michael Wright842500e2015-03-13 17:32:02 -07006838void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006839 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006840 outState->rawPointerData.pointerCount = 1;
6841 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006842
6843 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6844 && (mTouchButtonAccumulator.isHovering()
6845 || (mRawPointerAxes.pressure.valid
6846 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006847 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006848
Michael Wright842500e2015-03-13 17:32:02 -07006849 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006850 outPointer.id = 0;
6851 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6852 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6853 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6854 outPointer.touchMajor = 0;
6855 outPointer.touchMinor = 0;
6856 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6857 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6858 outPointer.orientation = 0;
6859 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6860 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6861 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6862 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6863 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6864 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6865 }
6866 outPointer.isHovering = isHovering;
6867 }
6868}
6869
6870void SingleTouchInputMapper::configureRawPointerAxes() {
6871 TouchInputMapper::configureRawPointerAxes();
6872
6873 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6874 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6875 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6876 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6877 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6878 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6879 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6880}
6881
6882bool SingleTouchInputMapper::hasStylus() const {
6883 return mTouchButtonAccumulator.hasStylus();
6884}
6885
6886
6887// --- MultiTouchInputMapper ---
6888
6889MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6890 TouchInputMapper(device) {
6891}
6892
6893MultiTouchInputMapper::~MultiTouchInputMapper() {
6894}
6895
6896void MultiTouchInputMapper::reset(nsecs_t when) {
6897 mMultiTouchMotionAccumulator.reset(getDevice());
6898
6899 mPointerIdBits.clear();
6900
6901 TouchInputMapper::reset(when);
6902}
6903
6904void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6905 TouchInputMapper::process(rawEvent);
6906
6907 mMultiTouchMotionAccumulator.process(rawEvent);
6908}
6909
Michael Wright842500e2015-03-13 17:32:02 -07006910void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006911 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6912 size_t outCount = 0;
6913 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006914 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006915
6916 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6917 const MultiTouchMotionAccumulator::Slot* inSlot =
6918 mMultiTouchMotionAccumulator.getSlot(inIndex);
6919 if (!inSlot->isInUse()) {
6920 continue;
6921 }
6922
6923 if (outCount >= MAX_POINTERS) {
6924#if DEBUG_POINTERS
6925 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6926 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006927 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006928#endif
6929 break; // too many fingers!
6930 }
6931
Michael Wright842500e2015-03-13 17:32:02 -07006932 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006933 outPointer.x = inSlot->getX();
6934 outPointer.y = inSlot->getY();
6935 outPointer.pressure = inSlot->getPressure();
6936 outPointer.touchMajor = inSlot->getTouchMajor();
6937 outPointer.touchMinor = inSlot->getTouchMinor();
6938 outPointer.toolMajor = inSlot->getToolMajor();
6939 outPointer.toolMinor = inSlot->getToolMinor();
6940 outPointer.orientation = inSlot->getOrientation();
6941 outPointer.distance = inSlot->getDistance();
6942 outPointer.tiltX = 0;
6943 outPointer.tiltY = 0;
6944
6945 outPointer.toolType = inSlot->getToolType();
6946 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6947 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6948 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6949 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6950 }
6951 }
6952
6953 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6954 && (mTouchButtonAccumulator.isHovering()
6955 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6956 outPointer.isHovering = isHovering;
6957
6958 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006959 if (mHavePointerIds) {
6960 int32_t trackingId = inSlot->getTrackingId();
6961 int32_t id = -1;
6962 if (trackingId >= 0) {
6963 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6964 uint32_t n = idBits.clearFirstMarkedBit();
6965 if (mPointerTrackingIdMap[n] == trackingId) {
6966 id = n;
6967 }
6968 }
6969
6970 if (id < 0 && !mPointerIdBits.isFull()) {
6971 id = mPointerIdBits.markFirstUnmarkedBit();
6972 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006973 }
Michael Wright842500e2015-03-13 17:32:02 -07006974 }
gaoshang1a632de2016-08-24 10:23:50 +08006975 if (id < 0) {
6976 mHavePointerIds = false;
6977 outState->rawPointerData.clearIdBits();
6978 newPointerIdBits.clear();
6979 } else {
6980 outPointer.id = id;
6981 outState->rawPointerData.idToIndex[id] = outCount;
6982 outState->rawPointerData.markIdBit(id, isHovering);
6983 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006984 }
Michael Wright842500e2015-03-13 17:32:02 -07006985 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006986 outCount += 1;
6987 }
6988
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006989 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006990 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006991 mPointerIdBits = newPointerIdBits;
6992
6993 mMultiTouchMotionAccumulator.finishSync();
6994}
6995
6996void MultiTouchInputMapper::configureRawPointerAxes() {
6997 TouchInputMapper::configureRawPointerAxes();
6998
6999 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
7000 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
7001 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
7002 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
7003 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
7004 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
7005 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
7006 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
7007 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
7008 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
7009 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
7010
7011 if (mRawPointerAxes.trackingId.valid
7012 && mRawPointerAxes.slot.valid
7013 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7014 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7015 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007016 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7017 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007018 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007019 slotCount = MAX_SLOTS;
7020 }
7021 mMultiTouchMotionAccumulator.configure(getDevice(),
7022 slotCount, true /*usingSlotsProtocol*/);
7023 } else {
7024 mMultiTouchMotionAccumulator.configure(getDevice(),
7025 MAX_POINTERS, false /*usingSlotsProtocol*/);
7026 }
7027}
7028
7029bool MultiTouchInputMapper::hasStylus() const {
7030 return mMultiTouchMotionAccumulator.hasStylus()
7031 || mTouchButtonAccumulator.hasStylus();
7032}
7033
Michael Wright842500e2015-03-13 17:32:02 -07007034// --- ExternalStylusInputMapper
7035
7036ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7037 InputMapper(device) {
7038
7039}
7040
7041uint32_t ExternalStylusInputMapper::getSources() {
7042 return AINPUT_SOURCE_STYLUS;
7043}
7044
7045void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7046 InputMapper::populateDeviceInfo(info);
7047 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7048 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7049}
7050
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007051void ExternalStylusInputMapper::dump(std::string& dump) {
7052 dump += INDENT2 "External Stylus Input Mapper:\n";
7053 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007054 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007055 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007056 dumpStylusState(dump, mStylusState);
7057}
7058
7059void ExternalStylusInputMapper::configure(nsecs_t when,
7060 const InputReaderConfiguration* config, uint32_t changes) {
7061 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7062 mTouchButtonAccumulator.configure(getDevice());
7063}
7064
7065void ExternalStylusInputMapper::reset(nsecs_t when) {
7066 InputDevice* device = getDevice();
7067 mSingleTouchMotionAccumulator.reset(device);
7068 mTouchButtonAccumulator.reset(device);
7069 InputMapper::reset(when);
7070}
7071
7072void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7073 mSingleTouchMotionAccumulator.process(rawEvent);
7074 mTouchButtonAccumulator.process(rawEvent);
7075
7076 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7077 sync(rawEvent->when);
7078 }
7079}
7080
7081void ExternalStylusInputMapper::sync(nsecs_t when) {
7082 mStylusState.clear();
7083
7084 mStylusState.when = when;
7085
Michael Wright45ccacf2015-04-21 19:01:58 +01007086 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7087 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7088 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7089 }
7090
Michael Wright842500e2015-03-13 17:32:02 -07007091 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7092 if (mRawPressureAxis.valid) {
7093 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7094 } else if (mTouchButtonAccumulator.isToolActive()) {
7095 mStylusState.pressure = 1.0f;
7096 } else {
7097 mStylusState.pressure = 0.0f;
7098 }
7099
7100 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007101
7102 mContext->dispatchExternalStylusState(mStylusState);
7103}
7104
Michael Wrightd02c5b62014-02-10 15:10:22 -08007105
7106// --- JoystickInputMapper ---
7107
7108JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7109 InputMapper(device) {
7110}
7111
7112JoystickInputMapper::~JoystickInputMapper() {
7113}
7114
7115uint32_t JoystickInputMapper::getSources() {
7116 return AINPUT_SOURCE_JOYSTICK;
7117}
7118
7119void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7120 InputMapper::populateDeviceInfo(info);
7121
7122 for (size_t i = 0; i < mAxes.size(); i++) {
7123 const Axis& axis = mAxes.valueAt(i);
7124 addMotionRange(axis.axisInfo.axis, axis, info);
7125
7126 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7127 addMotionRange(axis.axisInfo.highAxis, axis, info);
7128
7129 }
7130 }
7131}
7132
7133void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7134 InputDeviceInfo* info) {
7135 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7136 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7137 /* In order to ease the transition for developers from using the old axes
7138 * to the newer, more semantically correct axes, we'll continue to register
7139 * the old axes as duplicates of their corresponding new ones. */
7140 int32_t compatAxis = getCompatAxis(axisId);
7141 if (compatAxis >= 0) {
7142 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7143 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7144 }
7145}
7146
7147/* A mapping from axes the joystick actually has to the axes that should be
7148 * artificially created for compatibility purposes.
7149 * Returns -1 if no compatibility axis is needed. */
7150int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7151 switch(axis) {
7152 case AMOTION_EVENT_AXIS_LTRIGGER:
7153 return AMOTION_EVENT_AXIS_BRAKE;
7154 case AMOTION_EVENT_AXIS_RTRIGGER:
7155 return AMOTION_EVENT_AXIS_GAS;
7156 }
7157 return -1;
7158}
7159
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007160void JoystickInputMapper::dump(std::string& dump) {
7161 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007162
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007163 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007164 size_t numAxes = mAxes.size();
7165 for (size_t i = 0; i < numAxes; i++) {
7166 const Axis& axis = mAxes.valueAt(i);
7167 const char* label = getAxisLabel(axis.axisInfo.axis);
7168 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007169 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007170 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007171 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007172 }
7173 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7174 label = getAxisLabel(axis.axisInfo.highAxis);
7175 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007176 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007177 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007178 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007179 axis.axisInfo.splitValue);
7180 }
7181 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007182 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007183 }
7184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007185 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 -08007186 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007187 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007188 "highScale=%0.5f, highOffset=%0.5f\n",
7189 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007190 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007191 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7192 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7193 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7194 }
7195}
7196
7197void JoystickInputMapper::configure(nsecs_t when,
7198 const InputReaderConfiguration* config, uint32_t changes) {
7199 InputMapper::configure(when, config, changes);
7200
7201 if (!changes) { // first time only
7202 // Collect all axes.
7203 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7204 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7205 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7206 continue; // axis must be claimed by a different device
7207 }
7208
7209 RawAbsoluteAxisInfo rawAxisInfo;
7210 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7211 if (rawAxisInfo.valid) {
7212 // Map axis.
7213 AxisInfo axisInfo;
7214 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7215 if (!explicitlyMapped) {
7216 // Axis is not explicitly mapped, will choose a generic axis later.
7217 axisInfo.mode = AxisInfo::MODE_NORMAL;
7218 axisInfo.axis = -1;
7219 }
7220
7221 // Apply flat override.
7222 int32_t rawFlat = axisInfo.flatOverride < 0
7223 ? rawAxisInfo.flat : axisInfo.flatOverride;
7224
7225 // Calculate scaling factors and limits.
7226 Axis axis;
7227 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7228 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7229 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7230 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7231 scale, 0.0f, highScale, 0.0f,
7232 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7233 rawAxisInfo.resolution * scale);
7234 } else if (isCenteredAxis(axisInfo.axis)) {
7235 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7236 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7237 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7238 scale, offset, scale, offset,
7239 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7240 rawAxisInfo.resolution * scale);
7241 } else {
7242 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7243 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7244 scale, 0.0f, scale, 0.0f,
7245 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7246 rawAxisInfo.resolution * scale);
7247 }
7248
7249 // To eliminate noise while the joystick is at rest, filter out small variations
7250 // in axis values up front.
7251 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7252
7253 mAxes.add(abs, axis);
7254 }
7255 }
7256
7257 // If there are too many axes, start dropping them.
7258 // Prefer to keep explicitly mapped axes.
7259 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007260 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007261 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007262 pruneAxes(true);
7263 pruneAxes(false);
7264 }
7265
7266 // Assign generic axis ids to remaining axes.
7267 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7268 size_t numAxes = mAxes.size();
7269 for (size_t i = 0; i < numAxes; i++) {
7270 Axis& axis = mAxes.editValueAt(i);
7271 if (axis.axisInfo.axis < 0) {
7272 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7273 && haveAxis(nextGenericAxisId)) {
7274 nextGenericAxisId += 1;
7275 }
7276
7277 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7278 axis.axisInfo.axis = nextGenericAxisId;
7279 nextGenericAxisId += 1;
7280 } else {
7281 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7282 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007283 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007284 mAxes.removeItemsAt(i--);
7285 numAxes -= 1;
7286 }
7287 }
7288 }
7289 }
7290}
7291
7292bool JoystickInputMapper::haveAxis(int32_t axisId) {
7293 size_t numAxes = mAxes.size();
7294 for (size_t i = 0; i < numAxes; i++) {
7295 const Axis& axis = mAxes.valueAt(i);
7296 if (axis.axisInfo.axis == axisId
7297 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7298 && axis.axisInfo.highAxis == axisId)) {
7299 return true;
7300 }
7301 }
7302 return false;
7303}
7304
7305void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7306 size_t i = mAxes.size();
7307 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7308 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7309 continue;
7310 }
7311 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007312 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007313 mAxes.removeItemsAt(i);
7314 }
7315}
7316
7317bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7318 switch (axis) {
7319 case AMOTION_EVENT_AXIS_X:
7320 case AMOTION_EVENT_AXIS_Y:
7321 case AMOTION_EVENT_AXIS_Z:
7322 case AMOTION_EVENT_AXIS_RX:
7323 case AMOTION_EVENT_AXIS_RY:
7324 case AMOTION_EVENT_AXIS_RZ:
7325 case AMOTION_EVENT_AXIS_HAT_X:
7326 case AMOTION_EVENT_AXIS_HAT_Y:
7327 case AMOTION_EVENT_AXIS_ORIENTATION:
7328 case AMOTION_EVENT_AXIS_RUDDER:
7329 case AMOTION_EVENT_AXIS_WHEEL:
7330 return true;
7331 default:
7332 return false;
7333 }
7334}
7335
7336void JoystickInputMapper::reset(nsecs_t when) {
7337 // Recenter all axes.
7338 size_t numAxes = mAxes.size();
7339 for (size_t i = 0; i < numAxes; i++) {
7340 Axis& axis = mAxes.editValueAt(i);
7341 axis.resetValue();
7342 }
7343
7344 InputMapper::reset(when);
7345}
7346
7347void JoystickInputMapper::process(const RawEvent* rawEvent) {
7348 switch (rawEvent->type) {
7349 case EV_ABS: {
7350 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7351 if (index >= 0) {
7352 Axis& axis = mAxes.editValueAt(index);
7353 float newValue, highNewValue;
7354 switch (axis.axisInfo.mode) {
7355 case AxisInfo::MODE_INVERT:
7356 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7357 * axis.scale + axis.offset;
7358 highNewValue = 0.0f;
7359 break;
7360 case AxisInfo::MODE_SPLIT:
7361 if (rawEvent->value < axis.axisInfo.splitValue) {
7362 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7363 * axis.scale + axis.offset;
7364 highNewValue = 0.0f;
7365 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7366 newValue = 0.0f;
7367 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7368 * axis.highScale + axis.highOffset;
7369 } else {
7370 newValue = 0.0f;
7371 highNewValue = 0.0f;
7372 }
7373 break;
7374 default:
7375 newValue = rawEvent->value * axis.scale + axis.offset;
7376 highNewValue = 0.0f;
7377 break;
7378 }
7379 axis.newValue = newValue;
7380 axis.highNewValue = highNewValue;
7381 }
7382 break;
7383 }
7384
7385 case EV_SYN:
7386 switch (rawEvent->code) {
7387 case SYN_REPORT:
7388 sync(rawEvent->when, false /*force*/);
7389 break;
7390 }
7391 break;
7392 }
7393}
7394
7395void JoystickInputMapper::sync(nsecs_t when, bool force) {
7396 if (!filterAxes(force)) {
7397 return;
7398 }
7399
7400 int32_t metaState = mContext->getGlobalMetaState();
7401 int32_t buttonState = 0;
7402
7403 PointerProperties pointerProperties;
7404 pointerProperties.clear();
7405 pointerProperties.id = 0;
7406 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7407
7408 PointerCoords pointerCoords;
7409 pointerCoords.clear();
7410
7411 size_t numAxes = mAxes.size();
7412 for (size_t i = 0; i < numAxes; i++) {
7413 const Axis& axis = mAxes.valueAt(i);
7414 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7415 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7416 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7417 axis.highCurrentValue);
7418 }
7419 }
7420
7421 // Moving a joystick axis should not wake the device because joysticks can
7422 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7423 // button will likely wake the device.
7424 // TODO: Use the input device configuration to control this behavior more finely.
7425 uint32_t policyFlags = 0;
7426
Prabir Pradhan42611e02018-11-27 14:04:02 -08007427 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7428 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Siarhei Vishniakouae478d32019-01-03 14:45:18 -08007429 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, MotionClassification::NONE,
7430 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0, 1,
7431 &pointerProperties, &pointerCoords, 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007432 getListener()->notifyMotion(&args);
7433}
7434
7435void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7436 int32_t axis, float value) {
7437 pointerCoords->setAxisValue(axis, value);
7438 /* In order to ease the transition for developers from using the old axes
7439 * to the newer, more semantically correct axes, we'll continue to produce
7440 * values for the old axes as mirrors of the value of their corresponding
7441 * new axes. */
7442 int32_t compatAxis = getCompatAxis(axis);
7443 if (compatAxis >= 0) {
7444 pointerCoords->setAxisValue(compatAxis, value);
7445 }
7446}
7447
7448bool JoystickInputMapper::filterAxes(bool force) {
7449 bool atLeastOneSignificantChange = force;
7450 size_t numAxes = mAxes.size();
7451 for (size_t i = 0; i < numAxes; i++) {
7452 Axis& axis = mAxes.editValueAt(i);
7453 if (force || hasValueChangedSignificantly(axis.filter,
7454 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7455 axis.currentValue = axis.newValue;
7456 atLeastOneSignificantChange = true;
7457 }
7458 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7459 if (force || hasValueChangedSignificantly(axis.filter,
7460 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7461 axis.highCurrentValue = axis.highNewValue;
7462 atLeastOneSignificantChange = true;
7463 }
7464 }
7465 }
7466 return atLeastOneSignificantChange;
7467}
7468
7469bool JoystickInputMapper::hasValueChangedSignificantly(
7470 float filter, float newValue, float currentValue, float min, float max) {
7471 if (newValue != currentValue) {
7472 // Filter out small changes in value unless the value is converging on the axis
7473 // bounds or center point. This is intended to reduce the amount of information
7474 // sent to applications by particularly noisy joysticks (such as PS3).
7475 if (fabs(newValue - currentValue) > filter
7476 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7477 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7478 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7479 return true;
7480 }
7481 }
7482 return false;
7483}
7484
7485bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7486 float filter, float newValue, float currentValue, float thresholdValue) {
7487 float newDistance = fabs(newValue - thresholdValue);
7488 if (newDistance < filter) {
7489 float oldDistance = fabs(currentValue - thresholdValue);
7490 if (newDistance < oldDistance) {
7491 return true;
7492 }
7493 }
7494 return false;
7495}
7496
7497} // namespace android