blob: 3d5f1d92d531ab408c574706addd096eb82e9d90 [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 }
2644 bumpGeneration();
2645 }
2646}
2647
2648void CursorInputMapper::configureParameters() {
2649 mParameters.mode = Parameters::MODE_POINTER;
2650 String8 cursorModeString;
2651 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2652 if (cursorModeString == "navigation") {
2653 mParameters.mode = Parameters::MODE_NAVIGATION;
2654 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2655 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2656 }
2657 }
2658
2659 mParameters.orientationAware = false;
2660 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2661 mParameters.orientationAware);
2662
2663 mParameters.hasAssociatedDisplay = false;
2664 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2665 mParameters.hasAssociatedDisplay = true;
2666 }
2667}
2668
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002669void CursorInputMapper::dumpParameters(std::string& dump) {
2670 dump += INDENT3 "Parameters:\n";
2671 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002672 toString(mParameters.hasAssociatedDisplay));
2673
2674 switch (mParameters.mode) {
2675 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002676 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002678 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002679 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002680 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002681 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002682 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002683 break;
2684 default:
2685 ALOG_ASSERT(false);
2686 }
2687
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002688 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002689 toString(mParameters.orientationAware));
2690}
2691
2692void CursorInputMapper::reset(nsecs_t when) {
2693 mButtonState = 0;
2694 mDownTime = 0;
2695
2696 mPointerVelocityControl.reset();
2697 mWheelXVelocityControl.reset();
2698 mWheelYVelocityControl.reset();
2699
2700 mCursorButtonAccumulator.reset(getDevice());
2701 mCursorMotionAccumulator.reset(getDevice());
2702 mCursorScrollAccumulator.reset(getDevice());
2703
2704 InputMapper::reset(when);
2705}
2706
2707void CursorInputMapper::process(const RawEvent* rawEvent) {
2708 mCursorButtonAccumulator.process(rawEvent);
2709 mCursorMotionAccumulator.process(rawEvent);
2710 mCursorScrollAccumulator.process(rawEvent);
2711
2712 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2713 sync(rawEvent->when);
2714 }
2715}
2716
2717void CursorInputMapper::sync(nsecs_t when) {
2718 int32_t lastButtonState = mButtonState;
2719 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2720 mButtonState = currentButtonState;
2721
2722 bool wasDown = isPointerDown(lastButtonState);
2723 bool down = isPointerDown(currentButtonState);
2724 bool downChanged;
2725 if (!wasDown && down) {
2726 mDownTime = when;
2727 downChanged = true;
2728 } else if (wasDown && !down) {
2729 downChanged = true;
2730 } else {
2731 downChanged = false;
2732 }
2733 nsecs_t downTime = mDownTime;
2734 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002735 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2736 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002737
2738 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2739 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2740 bool moved = deltaX != 0 || deltaY != 0;
2741
2742 // Rotate delta according to orientation if needed.
2743 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2744 && (deltaX != 0.0f || deltaY != 0.0f)) {
2745 rotateDelta(mOrientation, &deltaX, &deltaY);
2746 }
2747
2748 // Move the pointer.
2749 PointerProperties pointerProperties;
2750 pointerProperties.clear();
2751 pointerProperties.id = 0;
2752 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2753
2754 PointerCoords pointerCoords;
2755 pointerCoords.clear();
2756
2757 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2758 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2759 bool scrolled = vscroll != 0 || hscroll != 0;
2760
Yi Kong9b14ac62018-07-17 13:48:38 -07002761 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2762 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002763
2764 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2765
2766 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002767 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002768 if (moved || scrolled || buttonsChanged) {
2769 mPointerController->setPresentation(
2770 PointerControllerInterface::PRESENTATION_POINTER);
2771
2772 if (moved) {
2773 mPointerController->move(deltaX, deltaY);
2774 }
2775
2776 if (buttonsChanged) {
2777 mPointerController->setButtonState(currentButtonState);
2778 }
2779
2780 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2781 }
2782
2783 float x, y;
2784 mPointerController->getPosition(&x, &y);
2785 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2786 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002787 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2788 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Dan Harmsaca28402018-12-17 13:55:20 -08002789 displayId = ADISPLAY_ID_DEFAULT;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002790 } else {
2791 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2792 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2793 displayId = ADISPLAY_ID_NONE;
2794 }
2795
2796 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2797
2798 // Moving an external trackball or mouse should wake the device.
2799 // We don't do this for internal cursor devices to prevent them from waking up
2800 // the device in your pocket.
2801 // TODO: Use the input device configuration to control this behavior more finely.
2802 uint32_t policyFlags = 0;
2803 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002804 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002805 }
2806
2807 // Synthesize key down from buttons if needed.
2808 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002809 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002810
2811 // Send motion event.
2812 if (downChanged || moved || scrolled || buttonsChanged) {
2813 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002814 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002815 int32_t motionEventAction;
2816 if (downChanged) {
2817 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002818 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2820 } else {
2821 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2822 }
2823
Michael Wright7b159c92015-05-14 14:48:03 +01002824 if (buttonsReleased) {
2825 BitSet32 released(buttonsReleased);
2826 while (!released.isEmpty()) {
2827 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2828 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002829 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2830 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002831 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2832 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002833 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002834 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002835 getListener()->notifyMotion(&releaseArgs);
2836 }
2837 }
2838
Prabir Pradhan42611e02018-11-27 14:04:02 -08002839 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2840 displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
Michael Wright7b159c92015-05-14 14:48:03 +01002841 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002842 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002843 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002844 getListener()->notifyMotion(&args);
2845
Michael Wright7b159c92015-05-14 14:48:03 +01002846 if (buttonsPressed) {
2847 BitSet32 pressed(buttonsPressed);
2848 while (!pressed.isEmpty()) {
2849 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2850 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002851 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2852 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2853 actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002854 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002855 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002856 getListener()->notifyMotion(&pressArgs);
2857 }
2858 }
2859
2860 ALOG_ASSERT(buttonState == currentButtonState);
2861
Michael Wrightd02c5b62014-02-10 15:10:22 -08002862 // Send hover move after UP to tell the application that the mouse is hovering now.
2863 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002864 && (mSource == AINPUT_SOURCE_MOUSE)) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08002865 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2866 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002867 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002868 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002869 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002870 getListener()->notifyMotion(&hoverArgs);
2871 }
2872
2873 // Send scroll events.
2874 if (scrolled) {
2875 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2876 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2877
Prabir Pradhan42611e02018-11-27 14:04:02 -08002878 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
2879 mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002880 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002882 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08002883 mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002884 getListener()->notifyMotion(&scrollArgs);
2885 }
2886 }
2887
2888 // Synthesize key up from buttons if needed.
2889 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002890 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002891
2892 mCursorMotionAccumulator.finishSync();
2893 mCursorScrollAccumulator.finishSync();
2894}
2895
2896int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2897 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2898 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2899 } else {
2900 return AKEY_STATE_UNKNOWN;
2901 }
2902}
2903
2904void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002905 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002906 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2907 }
2908}
2909
Prashant Malani1941ff52015-08-11 18:29:28 -07002910// --- RotaryEncoderInputMapper ---
2911
2912RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002913 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002914 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2915}
2916
2917RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2918}
2919
2920uint32_t RotaryEncoderInputMapper::getSources() {
2921 return mSource;
2922}
2923
2924void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2925 InputMapper::populateDeviceInfo(info);
2926
2927 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002928 float res = 0.0f;
2929 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2930 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2931 }
2932 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2933 mScalingFactor)) {
2934 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2935 "default to 1.0!\n");
2936 mScalingFactor = 1.0f;
2937 }
2938 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2939 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002940 }
2941}
2942
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002943void RotaryEncoderInputMapper::dump(std::string& dump) {
2944 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2945 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002946 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2947}
2948
2949void RotaryEncoderInputMapper::configure(nsecs_t when,
2950 const InputReaderConfiguration* config, uint32_t changes) {
2951 InputMapper::configure(when, config, changes);
2952 if (!changes) {
2953 mRotaryEncoderScrollAccumulator.configure(getDevice());
2954 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002955 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002956 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002957 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002958 if (internalViewport) {
2959 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002960 } else {
2961 mOrientation = DISPLAY_ORIENTATION_0;
2962 }
2963 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002964}
2965
2966void RotaryEncoderInputMapper::reset(nsecs_t when) {
2967 mRotaryEncoderScrollAccumulator.reset(getDevice());
2968
2969 InputMapper::reset(when);
2970}
2971
2972void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2973 mRotaryEncoderScrollAccumulator.process(rawEvent);
2974
2975 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2976 sync(rawEvent->when);
2977 }
2978}
2979
2980void RotaryEncoderInputMapper::sync(nsecs_t when) {
2981 PointerCoords pointerCoords;
2982 pointerCoords.clear();
2983
2984 PointerProperties pointerProperties;
2985 pointerProperties.clear();
2986 pointerProperties.id = 0;
2987 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2988
2989 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2990 bool scrolled = scroll != 0;
2991
2992 // This is not a pointer, so it's not associated with a display.
2993 int32_t displayId = ADISPLAY_ID_NONE;
2994
2995 // Moving the rotary encoder should wake the device (if specified).
2996 uint32_t policyFlags = 0;
2997 if (scrolled && getDevice()->isExternal()) {
2998 policyFlags |= POLICY_FLAG_WAKE;
2999 }
3000
Ivan Podogovad437252016-09-29 16:29:55 +01003001 if (mOrientation == DISPLAY_ORIENTATION_180) {
3002 scroll = -scroll;
3003 }
3004
Prashant Malani1941ff52015-08-11 18:29:28 -07003005 // Send motion event.
3006 if (scrolled) {
3007 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003008 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003009
Prabir Pradhan42611e02018-11-27 14:04:02 -08003010 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
3011 mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003012 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3013 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003014 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08003015 0, 0, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003016 getListener()->notifyMotion(&scrollArgs);
3017 }
3018
3019 mRotaryEncoderScrollAccumulator.finishSync();
3020}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003021
3022// --- TouchInputMapper ---
3023
3024TouchInputMapper::TouchInputMapper(InputDevice* device) :
3025 InputMapper(device),
3026 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3027 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003028 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003029 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3030}
3031
3032TouchInputMapper::~TouchInputMapper() {
3033}
3034
3035uint32_t TouchInputMapper::getSources() {
3036 return mSource;
3037}
3038
3039void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3040 InputMapper::populateDeviceInfo(info);
3041
3042 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3043 info->addMotionRange(mOrientedRanges.x);
3044 info->addMotionRange(mOrientedRanges.y);
3045 info->addMotionRange(mOrientedRanges.pressure);
3046
3047 if (mOrientedRanges.haveSize) {
3048 info->addMotionRange(mOrientedRanges.size);
3049 }
3050
3051 if (mOrientedRanges.haveTouchSize) {
3052 info->addMotionRange(mOrientedRanges.touchMajor);
3053 info->addMotionRange(mOrientedRanges.touchMinor);
3054 }
3055
3056 if (mOrientedRanges.haveToolSize) {
3057 info->addMotionRange(mOrientedRanges.toolMajor);
3058 info->addMotionRange(mOrientedRanges.toolMinor);
3059 }
3060
3061 if (mOrientedRanges.haveOrientation) {
3062 info->addMotionRange(mOrientedRanges.orientation);
3063 }
3064
3065 if (mOrientedRanges.haveDistance) {
3066 info->addMotionRange(mOrientedRanges.distance);
3067 }
3068
3069 if (mOrientedRanges.haveTilt) {
3070 info->addMotionRange(mOrientedRanges.tilt);
3071 }
3072
3073 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3074 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3075 0.0f);
3076 }
3077 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3078 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3079 0.0f);
3080 }
3081 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3082 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3083 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3084 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3085 x.fuzz, x.resolution);
3086 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3087 y.fuzz, y.resolution);
3088 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3089 x.fuzz, x.resolution);
3090 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3091 y.fuzz, y.resolution);
3092 }
3093 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3094 }
3095}
3096
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003097void TouchInputMapper::dump(std::string& dump) {
3098 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003099 dumpParameters(dump);
3100 dumpVirtualKeys(dump);
3101 dumpRawPointerAxes(dump);
3102 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003103 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 dumpSurface(dump);
3105
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003106 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3107 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3108 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3109 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3110 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3111 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3112 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3113 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3114 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3115 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3116 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3117 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3118 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3119 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3120 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3121 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3122 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003123
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003124 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3125 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003126 mLastRawState.rawPointerData.pointerCount);
3127 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3128 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003129 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003130 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3131 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3132 "toolType=%d, isHovering=%s\n", i,
3133 pointer.id, pointer.x, pointer.y, pointer.pressure,
3134 pointer.touchMajor, pointer.touchMinor,
3135 pointer.toolMajor, pointer.toolMinor,
3136 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3137 pointer.toolType, toString(pointer.isHovering));
3138 }
3139
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003140 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3141 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003142 mLastCookedState.cookedPointerData.pointerCount);
3143 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3144 const PointerProperties& pointerProperties =
3145 mLastCookedState.cookedPointerData.pointerProperties[i];
3146 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003147 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3149 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3150 "toolType=%d, isHovering=%s\n", i,
3151 pointerProperties.id,
3152 pointerCoords.getX(),
3153 pointerCoords.getY(),
3154 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3155 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3156 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3157 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3158 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3159 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3160 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3161 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3162 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003163 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003164 }
3165
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003166 dump += INDENT3 "Stylus Fusion:\n";
3167 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003168 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003169 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3170 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003171 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003172 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003173 dumpStylusState(dump, mExternalStylusState);
3174
Michael Wrightd02c5b62014-02-10 15:10:22 -08003175 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003176 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3177 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003179 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003181 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003182 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003183 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003184 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003185 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003186 mPointerGestureMaxSwipeWidth);
3187 }
3188}
3189
Santos Cordonfa5cf462017-04-05 10:37:00 -07003190const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3191 switch (deviceMode) {
3192 case DEVICE_MODE_DISABLED:
3193 return "disabled";
3194 case DEVICE_MODE_DIRECT:
3195 return "direct";
3196 case DEVICE_MODE_UNSCALED:
3197 return "unscaled";
3198 case DEVICE_MODE_NAVIGATION:
3199 return "navigation";
3200 case DEVICE_MODE_POINTER:
3201 return "pointer";
3202 }
3203 return "unknown";
3204}
3205
Michael Wrightd02c5b62014-02-10 15:10:22 -08003206void TouchInputMapper::configure(nsecs_t when,
3207 const InputReaderConfiguration* config, uint32_t changes) {
3208 InputMapper::configure(when, config, changes);
3209
3210 mConfig = *config;
3211
3212 if (!changes) { // first time only
3213 // Configure basic parameters.
3214 configureParameters();
3215
3216 // Configure common accumulators.
3217 mCursorScrollAccumulator.configure(getDevice());
3218 mTouchButtonAccumulator.configure(getDevice());
3219
3220 // Configure absolute axis information.
3221 configureRawPointerAxes();
3222
3223 // Prepare input device calibration.
3224 parseCalibration();
3225 resolveCalibration();
3226 }
3227
Michael Wright842500e2015-03-13 17:32:02 -07003228 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003229 // Update location calibration to reflect current settings
3230 updateAffineTransformation();
3231 }
3232
Michael Wrightd02c5b62014-02-10 15:10:22 -08003233 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3234 // Update pointer speed.
3235 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3236 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3237 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3238 }
3239
3240 bool resetNeeded = false;
3241 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3242 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003243 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3244 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003245 // Configure device sources, surface dimensions, orientation and
3246 // scaling factors.
3247 configureSurface(when, &resetNeeded);
3248 }
3249
3250 if (changes && resetNeeded) {
3251 // Send reset, unless this is the first time the device has been configured,
3252 // in which case the reader will call reset itself after all mappers are ready.
3253 getDevice()->notifyReset(when);
3254 }
3255}
3256
Michael Wright842500e2015-03-13 17:32:02 -07003257void TouchInputMapper::resolveExternalStylusPresence() {
3258 Vector<InputDeviceInfo> devices;
3259 mContext->getExternalStylusDevices(devices);
3260 mExternalStylusConnected = !devices.isEmpty();
3261
3262 if (!mExternalStylusConnected) {
3263 resetExternalStylus();
3264 }
3265}
3266
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267void TouchInputMapper::configureParameters() {
3268 // Use the pointer presentation mode for devices that do not support distinct
3269 // multitouch. The spot-based presentation relies on being able to accurately
3270 // locate two or more fingers on the touch pad.
3271 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003272 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003273
3274 String8 gestureModeString;
3275 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3276 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003277 if (gestureModeString == "single-touch") {
3278 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3279 } else if (gestureModeString == "multi-touch") {
3280 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003281 } else if (gestureModeString != "default") {
3282 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3283 }
3284 }
3285
3286 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3287 // The device is a touch screen.
3288 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3289 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3290 // The device is a pointing device like a track pad.
3291 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3292 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3293 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3294 // The device is a cursor device with a touch pad attached.
3295 // By default don't use the touch pad to move the pointer.
3296 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3297 } else {
3298 // The device is a touch pad of unknown purpose.
3299 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3300 }
3301
3302 mParameters.hasButtonUnderPad=
3303 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3304
3305 String8 deviceTypeString;
3306 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3307 deviceTypeString)) {
3308 if (deviceTypeString == "touchScreen") {
3309 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3310 } else if (deviceTypeString == "touchPad") {
3311 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3312 } else if (deviceTypeString == "touchNavigation") {
3313 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3314 } else if (deviceTypeString == "pointer") {
3315 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3316 } else if (deviceTypeString != "default") {
3317 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3318 }
3319 }
3320
3321 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3322 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3323 mParameters.orientationAware);
3324
3325 mParameters.hasAssociatedDisplay = false;
3326 mParameters.associatedDisplayIsExternal = false;
3327 if (mParameters.orientationAware
3328 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3329 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3330 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003331 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3332 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003333 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003334 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003335 uniqueDisplayId);
3336 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003337 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003338 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003339 if (getDevice()->getAssociatedDisplayPort()) {
3340 mParameters.hasAssociatedDisplay = true;
3341 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003342
3343 // Initial downs on external touch devices should wake the device.
3344 // Normally we don't do this for internal touch screens to prevent them from waking
3345 // up in your pocket but you can enable it using the input device configuration.
3346 mParameters.wake = getDevice()->isExternal();
3347 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3348 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003349}
3350
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003351void TouchInputMapper::dumpParameters(std::string& dump) {
3352 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003353
3354 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003355 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003356 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003357 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003358 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003359 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003360 break;
3361 default:
3362 assert(false);
3363 }
3364
3365 switch (mParameters.deviceType) {
3366 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003367 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 break;
3369 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003370 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 break;
3372 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003373 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003374 break;
3375 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003376 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377 break;
3378 default:
3379 ALOG_ASSERT(false);
3380 }
3381
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003382 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003383 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003384 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003385 toString(mParameters.associatedDisplayIsExternal),
3386 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003387 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003388 toString(mParameters.orientationAware));
3389}
3390
3391void TouchInputMapper::configureRawPointerAxes() {
3392 mRawPointerAxes.clear();
3393}
3394
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003395void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3396 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003397 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3398 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3399 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3400 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3401 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3402 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3403 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3404 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3405 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3406 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3407 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3408 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3409 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3410}
3411
Michael Wright842500e2015-03-13 17:32:02 -07003412bool TouchInputMapper::hasExternalStylus() const {
3413 return mExternalStylusConnected;
3414}
3415
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003416/**
3417 * Determine which DisplayViewport to use.
3418 * 1. If display port is specified, return the matching viewport. If matching viewport not
3419 * found, then return.
3420 * 2. If a device has associated display, get the matching viewport by either unique id or by
3421 * the display type (internal or external).
3422 * 3. Otherwise, use a non-display viewport.
3423 */
3424std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3425 if (mParameters.hasAssociatedDisplay) {
3426 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3427 if (displayPort) {
3428 // Find the viewport that contains the same port
3429 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3430 if (!v) {
3431 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3432 "but the corresponding viewport is not found.",
3433 getDeviceName().c_str(), *displayPort);
3434 }
3435 return v;
3436 }
3437
3438 if (!mParameters.uniqueDisplayId.empty()) {
3439 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3440 }
3441
3442 ViewportType viewportTypeToUse;
3443 if (mParameters.associatedDisplayIsExternal) {
3444 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3445 } else {
3446 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3447 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003448
3449 std::optional<DisplayViewport> viewport =
3450 mConfig.getDisplayViewportByType(viewportTypeToUse);
3451 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3452 ALOGW("Input device %s should be associated with external display, "
3453 "fallback to internal one for the external viewport is not found.",
3454 getDeviceName().c_str());
3455 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3456 }
3457
3458 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003459 }
3460
3461 DisplayViewport newViewport;
3462 // Raw width and height in the natural orientation.
3463 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3464 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3465 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3466 return std::make_optional(newViewport);
3467}
3468
Michael Wrightd02c5b62014-02-10 15:10:22 -08003469void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3470 int32_t oldDeviceMode = mDeviceMode;
3471
Michael Wright842500e2015-03-13 17:32:02 -07003472 resolveExternalStylusPresence();
3473
Michael Wrightd02c5b62014-02-10 15:10:22 -08003474 // Determine device mode.
3475 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3476 && mConfig.pointerGesturesEnabled) {
3477 mSource = AINPUT_SOURCE_MOUSE;
3478 mDeviceMode = DEVICE_MODE_POINTER;
3479 if (hasStylus()) {
3480 mSource |= AINPUT_SOURCE_STYLUS;
3481 }
3482 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3483 && mParameters.hasAssociatedDisplay) {
3484 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3485 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003486 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003487 mSource |= AINPUT_SOURCE_STYLUS;
3488 }
Michael Wright2f78b682015-06-12 15:25:08 +01003489 if (hasExternalStylus()) {
3490 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3491 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003492 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3493 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3494 mDeviceMode = DEVICE_MODE_NAVIGATION;
3495 } else {
3496 mSource = AINPUT_SOURCE_TOUCHPAD;
3497 mDeviceMode = DEVICE_MODE_UNSCALED;
3498 }
3499
3500 // Ensure we have valid X and Y axes.
3501 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003502 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003503 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003504 mDeviceMode = DEVICE_MODE_DISABLED;
3505 return;
3506 }
3507
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003508 // Get associated display dimensions.
3509 std::optional<DisplayViewport> newViewport = findViewport();
3510 if (!newViewport) {
3511 ALOGI("Touch device '%s' could not query the properties of its associated "
3512 "display. The device will be inoperable until the display size "
3513 "becomes available.",
3514 getDeviceName().c_str());
3515 mDeviceMode = DEVICE_MODE_DISABLED;
3516 return;
3517 }
3518
Michael Wrightd02c5b62014-02-10 15:10:22 -08003519 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003520 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3521 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003522
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003523 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003525 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526
3527 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3528 // Convert rotated viewport to natural surface coordinates.
3529 int32_t naturalLogicalWidth, naturalLogicalHeight;
3530 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3531 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3532 int32_t naturalDeviceWidth, naturalDeviceHeight;
3533 switch (mViewport.orientation) {
3534 case DISPLAY_ORIENTATION_90:
3535 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3536 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3537 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3538 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3539 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3540 naturalPhysicalTop = mViewport.physicalLeft;
3541 naturalDeviceWidth = mViewport.deviceHeight;
3542 naturalDeviceHeight = mViewport.deviceWidth;
3543 break;
3544 case DISPLAY_ORIENTATION_180:
3545 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3546 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3547 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3548 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3549 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3550 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3551 naturalDeviceWidth = mViewport.deviceWidth;
3552 naturalDeviceHeight = mViewport.deviceHeight;
3553 break;
3554 case DISPLAY_ORIENTATION_270:
3555 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3556 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3557 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3558 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3559 naturalPhysicalLeft = mViewport.physicalTop;
3560 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3561 naturalDeviceWidth = mViewport.deviceHeight;
3562 naturalDeviceHeight = mViewport.deviceWidth;
3563 break;
3564 case DISPLAY_ORIENTATION_0:
3565 default:
3566 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3567 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3568 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3569 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3570 naturalPhysicalLeft = mViewport.physicalLeft;
3571 naturalPhysicalTop = mViewport.physicalTop;
3572 naturalDeviceWidth = mViewport.deviceWidth;
3573 naturalDeviceHeight = mViewport.deviceHeight;
3574 break;
3575 }
3576
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003577 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3578 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3579 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3580 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3581 }
3582
Michael Wright358bcc72018-08-21 04:01:07 +01003583 mPhysicalWidth = naturalPhysicalWidth;
3584 mPhysicalHeight = naturalPhysicalHeight;
3585 mPhysicalLeft = naturalPhysicalLeft;
3586 mPhysicalTop = naturalPhysicalTop;
3587
Michael Wrightd02c5b62014-02-10 15:10:22 -08003588 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3589 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3590 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3591 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3592
3593 mSurfaceOrientation = mParameters.orientationAware ?
3594 mViewport.orientation : DISPLAY_ORIENTATION_0;
3595 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003596 mPhysicalWidth = rawWidth;
3597 mPhysicalHeight = rawHeight;
3598 mPhysicalLeft = 0;
3599 mPhysicalTop = 0;
3600
Michael Wrightd02c5b62014-02-10 15:10:22 -08003601 mSurfaceWidth = rawWidth;
3602 mSurfaceHeight = rawHeight;
3603 mSurfaceLeft = 0;
3604 mSurfaceTop = 0;
3605 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3606 }
3607 }
3608
3609 // If moving between pointer modes, need to reset some state.
3610 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3611 if (deviceModeChanged) {
3612 mOrientedRanges.clear();
3613 }
3614
3615 // Create pointer controller if needed.
3616 if (mDeviceMode == DEVICE_MODE_POINTER ||
3617 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003618 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003619 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3620 }
3621 } else {
3622 mPointerController.clear();
3623 }
3624
3625 if (viewportChanged || deviceModeChanged) {
3626 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3627 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003628 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003629 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3630
3631 // Configure X and Y factors.
3632 mXScale = float(mSurfaceWidth) / rawWidth;
3633 mYScale = float(mSurfaceHeight) / rawHeight;
3634 mXTranslate = -mSurfaceLeft;
3635 mYTranslate = -mSurfaceTop;
3636 mXPrecision = 1.0f / mXScale;
3637 mYPrecision = 1.0f / mYScale;
3638
3639 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3640 mOrientedRanges.x.source = mSource;
3641 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3642 mOrientedRanges.y.source = mSource;
3643
3644 configureVirtualKeys();
3645
3646 // Scale factor for terms that are not oriented in a particular axis.
3647 // If the pixels are square then xScale == yScale otherwise we fake it
3648 // by choosing an average.
3649 mGeometricScale = avg(mXScale, mYScale);
3650
3651 // Size of diagonal axis.
3652 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3653
3654 // Size factors.
3655 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3656 if (mRawPointerAxes.touchMajor.valid
3657 && mRawPointerAxes.touchMajor.maxValue != 0) {
3658 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3659 } else if (mRawPointerAxes.toolMajor.valid
3660 && mRawPointerAxes.toolMajor.maxValue != 0) {
3661 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3662 } else {
3663 mSizeScale = 0.0f;
3664 }
3665
3666 mOrientedRanges.haveTouchSize = true;
3667 mOrientedRanges.haveToolSize = true;
3668 mOrientedRanges.haveSize = true;
3669
3670 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3671 mOrientedRanges.touchMajor.source = mSource;
3672 mOrientedRanges.touchMajor.min = 0;
3673 mOrientedRanges.touchMajor.max = diagonalSize;
3674 mOrientedRanges.touchMajor.flat = 0;
3675 mOrientedRanges.touchMajor.fuzz = 0;
3676 mOrientedRanges.touchMajor.resolution = 0;
3677
3678 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3679 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3680
3681 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3682 mOrientedRanges.toolMajor.source = mSource;
3683 mOrientedRanges.toolMajor.min = 0;
3684 mOrientedRanges.toolMajor.max = diagonalSize;
3685 mOrientedRanges.toolMajor.flat = 0;
3686 mOrientedRanges.toolMajor.fuzz = 0;
3687 mOrientedRanges.toolMajor.resolution = 0;
3688
3689 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3690 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3691
3692 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3693 mOrientedRanges.size.source = mSource;
3694 mOrientedRanges.size.min = 0;
3695 mOrientedRanges.size.max = 1.0;
3696 mOrientedRanges.size.flat = 0;
3697 mOrientedRanges.size.fuzz = 0;
3698 mOrientedRanges.size.resolution = 0;
3699 } else {
3700 mSizeScale = 0.0f;
3701 }
3702
3703 // Pressure factors.
3704 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003705 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3707 || mCalibration.pressureCalibration
3708 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3709 if (mCalibration.havePressureScale) {
3710 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003711 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003712 } else if (mRawPointerAxes.pressure.valid
3713 && mRawPointerAxes.pressure.maxValue != 0) {
3714 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3715 }
3716 }
3717
3718 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3719 mOrientedRanges.pressure.source = mSource;
3720 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003721 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003722 mOrientedRanges.pressure.flat = 0;
3723 mOrientedRanges.pressure.fuzz = 0;
3724 mOrientedRanges.pressure.resolution = 0;
3725
3726 // Tilt
3727 mTiltXCenter = 0;
3728 mTiltXScale = 0;
3729 mTiltYCenter = 0;
3730 mTiltYScale = 0;
3731 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3732 if (mHaveTilt) {
3733 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3734 mRawPointerAxes.tiltX.maxValue);
3735 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3736 mRawPointerAxes.tiltY.maxValue);
3737 mTiltXScale = M_PI / 180;
3738 mTiltYScale = M_PI / 180;
3739
3740 mOrientedRanges.haveTilt = true;
3741
3742 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3743 mOrientedRanges.tilt.source = mSource;
3744 mOrientedRanges.tilt.min = 0;
3745 mOrientedRanges.tilt.max = M_PI_2;
3746 mOrientedRanges.tilt.flat = 0;
3747 mOrientedRanges.tilt.fuzz = 0;
3748 mOrientedRanges.tilt.resolution = 0;
3749 }
3750
3751 // Orientation
3752 mOrientationScale = 0;
3753 if (mHaveTilt) {
3754 mOrientedRanges.haveOrientation = true;
3755
3756 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3757 mOrientedRanges.orientation.source = mSource;
3758 mOrientedRanges.orientation.min = -M_PI;
3759 mOrientedRanges.orientation.max = M_PI;
3760 mOrientedRanges.orientation.flat = 0;
3761 mOrientedRanges.orientation.fuzz = 0;
3762 mOrientedRanges.orientation.resolution = 0;
3763 } else if (mCalibration.orientationCalibration !=
3764 Calibration::ORIENTATION_CALIBRATION_NONE) {
3765 if (mCalibration.orientationCalibration
3766 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3767 if (mRawPointerAxes.orientation.valid) {
3768 if (mRawPointerAxes.orientation.maxValue > 0) {
3769 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3770 } else if (mRawPointerAxes.orientation.minValue < 0) {
3771 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3772 } else {
3773 mOrientationScale = 0;
3774 }
3775 }
3776 }
3777
3778 mOrientedRanges.haveOrientation = true;
3779
3780 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3781 mOrientedRanges.orientation.source = mSource;
3782 mOrientedRanges.orientation.min = -M_PI_2;
3783 mOrientedRanges.orientation.max = M_PI_2;
3784 mOrientedRanges.orientation.flat = 0;
3785 mOrientedRanges.orientation.fuzz = 0;
3786 mOrientedRanges.orientation.resolution = 0;
3787 }
3788
3789 // Distance
3790 mDistanceScale = 0;
3791 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3792 if (mCalibration.distanceCalibration
3793 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3794 if (mCalibration.haveDistanceScale) {
3795 mDistanceScale = mCalibration.distanceScale;
3796 } else {
3797 mDistanceScale = 1.0f;
3798 }
3799 }
3800
3801 mOrientedRanges.haveDistance = true;
3802
3803 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3804 mOrientedRanges.distance.source = mSource;
3805 mOrientedRanges.distance.min =
3806 mRawPointerAxes.distance.minValue * mDistanceScale;
3807 mOrientedRanges.distance.max =
3808 mRawPointerAxes.distance.maxValue * mDistanceScale;
3809 mOrientedRanges.distance.flat = 0;
3810 mOrientedRanges.distance.fuzz =
3811 mRawPointerAxes.distance.fuzz * mDistanceScale;
3812 mOrientedRanges.distance.resolution = 0;
3813 }
3814
3815 // Compute oriented precision, scales and ranges.
3816 // Note that the maximum value reported is an inclusive maximum value so it is one
3817 // unit less than the total width or height of surface.
3818 switch (mSurfaceOrientation) {
3819 case DISPLAY_ORIENTATION_90:
3820 case DISPLAY_ORIENTATION_270:
3821 mOrientedXPrecision = mYPrecision;
3822 mOrientedYPrecision = mXPrecision;
3823
3824 mOrientedRanges.x.min = mYTranslate;
3825 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3826 mOrientedRanges.x.flat = 0;
3827 mOrientedRanges.x.fuzz = 0;
3828 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3829
3830 mOrientedRanges.y.min = mXTranslate;
3831 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3832 mOrientedRanges.y.flat = 0;
3833 mOrientedRanges.y.fuzz = 0;
3834 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3835 break;
3836
3837 default:
3838 mOrientedXPrecision = mXPrecision;
3839 mOrientedYPrecision = mYPrecision;
3840
3841 mOrientedRanges.x.min = mXTranslate;
3842 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3843 mOrientedRanges.x.flat = 0;
3844 mOrientedRanges.x.fuzz = 0;
3845 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3846
3847 mOrientedRanges.y.min = mYTranslate;
3848 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3849 mOrientedRanges.y.flat = 0;
3850 mOrientedRanges.y.fuzz = 0;
3851 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3852 break;
3853 }
3854
Jason Gerecke71b16e82014-03-10 09:47:59 -07003855 // Location
3856 updateAffineTransformation();
3857
Michael Wrightd02c5b62014-02-10 15:10:22 -08003858 if (mDeviceMode == DEVICE_MODE_POINTER) {
3859 // Compute pointer gesture detection parameters.
3860 float rawDiagonal = hypotf(rawWidth, rawHeight);
3861 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3862
3863 // Scale movements such that one whole swipe of the touch pad covers a
3864 // given area relative to the diagonal size of the display when no acceleration
3865 // is applied.
3866 // Assume that the touch pad has a square aspect ratio such that movements in
3867 // X and Y of the same number of raw units cover the same physical distance.
3868 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3869 * displayDiagonal / rawDiagonal;
3870 mPointerYMovementScale = mPointerXMovementScale;
3871
3872 // Scale zooms to cover a smaller range of the display than movements do.
3873 // This value determines the area around the pointer that is affected by freeform
3874 // pointer gestures.
3875 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3876 * displayDiagonal / rawDiagonal;
3877 mPointerYZoomScale = mPointerXZoomScale;
3878
3879 // Max width between pointers to detect a swipe gesture is more than some fraction
3880 // of the diagonal axis of the touch pad. Touches that are wider than this are
3881 // translated into freeform gestures.
3882 mPointerGestureMaxSwipeWidth =
3883 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3884
3885 // Abort current pointer usages because the state has changed.
3886 abortPointerUsage(when, 0 /*policyFlags*/);
3887 }
3888
3889 // Inform the dispatcher about the changes.
3890 *outResetNeeded = true;
3891 bumpGeneration();
3892 }
3893}
3894
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003895void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003896 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003897 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3898 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3899 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3900 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003901 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3902 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3903 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3904 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003905 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003906}
3907
3908void TouchInputMapper::configureVirtualKeys() {
3909 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3910 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3911
3912 mVirtualKeys.clear();
3913
3914 if (virtualKeyDefinitions.size() == 0) {
3915 return;
3916 }
3917
3918 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3919
3920 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3921 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003922 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3923 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003924
3925 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3926 const VirtualKeyDefinition& virtualKeyDefinition =
3927 virtualKeyDefinitions[i];
3928
3929 mVirtualKeys.add();
3930 VirtualKey& virtualKey = mVirtualKeys.editTop();
3931
3932 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3933 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003934 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003935 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003936 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3937 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003938 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3939 virtualKey.scanCode);
3940 mVirtualKeys.pop(); // drop the key
3941 continue;
3942 }
3943
3944 virtualKey.keyCode = keyCode;
3945 virtualKey.flags = flags;
3946
3947 // convert the key definition's display coordinates into touch coordinates for a hit box
3948 int32_t halfWidth = virtualKeyDefinition.width / 2;
3949 int32_t halfHeight = virtualKeyDefinition.height / 2;
3950
3951 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3952 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3953 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3954 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3955 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3956 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3957 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3958 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3959 }
3960}
3961
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003962void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003963 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003964 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003965
3966 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3967 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003968 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003969 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3970 i, virtualKey.scanCode, virtualKey.keyCode,
3971 virtualKey.hitLeft, virtualKey.hitRight,
3972 virtualKey.hitTop, virtualKey.hitBottom);
3973 }
3974 }
3975}
3976
3977void TouchInputMapper::parseCalibration() {
3978 const PropertyMap& in = getDevice()->getConfiguration();
3979 Calibration& out = mCalibration;
3980
3981 // Size
3982 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3983 String8 sizeCalibrationString;
3984 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3985 if (sizeCalibrationString == "none") {
3986 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3987 } else if (sizeCalibrationString == "geometric") {
3988 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3989 } else if (sizeCalibrationString == "diameter") {
3990 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3991 } else if (sizeCalibrationString == "box") {
3992 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3993 } else if (sizeCalibrationString == "area") {
3994 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3995 } else if (sizeCalibrationString != "default") {
3996 ALOGW("Invalid value for touch.size.calibration: '%s'",
3997 sizeCalibrationString.string());
3998 }
3999 }
4000
4001 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
4002 out.sizeScale);
4003 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
4004 out.sizeBias);
4005 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
4006 out.sizeIsSummed);
4007
4008 // Pressure
4009 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4010 String8 pressureCalibrationString;
4011 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4012 if (pressureCalibrationString == "none") {
4013 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4014 } else if (pressureCalibrationString == "physical") {
4015 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4016 } else if (pressureCalibrationString == "amplitude") {
4017 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4018 } else if (pressureCalibrationString != "default") {
4019 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4020 pressureCalibrationString.string());
4021 }
4022 }
4023
4024 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4025 out.pressureScale);
4026
4027 // Orientation
4028 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4029 String8 orientationCalibrationString;
4030 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4031 if (orientationCalibrationString == "none") {
4032 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4033 } else if (orientationCalibrationString == "interpolated") {
4034 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4035 } else if (orientationCalibrationString == "vector") {
4036 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4037 } else if (orientationCalibrationString != "default") {
4038 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4039 orientationCalibrationString.string());
4040 }
4041 }
4042
4043 // Distance
4044 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4045 String8 distanceCalibrationString;
4046 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4047 if (distanceCalibrationString == "none") {
4048 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4049 } else if (distanceCalibrationString == "scaled") {
4050 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4051 } else if (distanceCalibrationString != "default") {
4052 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4053 distanceCalibrationString.string());
4054 }
4055 }
4056
4057 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4058 out.distanceScale);
4059
4060 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4061 String8 coverageCalibrationString;
4062 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4063 if (coverageCalibrationString == "none") {
4064 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4065 } else if (coverageCalibrationString == "box") {
4066 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4067 } else if (coverageCalibrationString != "default") {
4068 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4069 coverageCalibrationString.string());
4070 }
4071 }
4072}
4073
4074void TouchInputMapper::resolveCalibration() {
4075 // Size
4076 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4077 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4078 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4079 }
4080 } else {
4081 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4082 }
4083
4084 // Pressure
4085 if (mRawPointerAxes.pressure.valid) {
4086 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4087 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4088 }
4089 } else {
4090 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4091 }
4092
4093 // Orientation
4094 if (mRawPointerAxes.orientation.valid) {
4095 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4096 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4097 }
4098 } else {
4099 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4100 }
4101
4102 // Distance
4103 if (mRawPointerAxes.distance.valid) {
4104 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4105 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4106 }
4107 } else {
4108 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4109 }
4110
4111 // Coverage
4112 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4113 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4114 }
4115}
4116
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004117void TouchInputMapper::dumpCalibration(std::string& dump) {
4118 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004119
4120 // Size
4121 switch (mCalibration.sizeCalibration) {
4122 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004123 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 break;
4125 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 break;
4128 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004129 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004130 break;
4131 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004132 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 break;
4134 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 break;
4137 default:
4138 ALOG_ASSERT(false);
4139 }
4140
4141 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004142 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 mCalibration.sizeScale);
4144 }
4145
4146 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004147 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004148 mCalibration.sizeBias);
4149 }
4150
4151 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004152 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004153 toString(mCalibration.sizeIsSummed));
4154 }
4155
4156 // Pressure
4157 switch (mCalibration.pressureCalibration) {
4158 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004159 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004160 break;
4161 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004162 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004163 break;
4164 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004165 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 break;
4167 default:
4168 ALOG_ASSERT(false);
4169 }
4170
4171 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004172 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004173 mCalibration.pressureScale);
4174 }
4175
4176 // Orientation
4177 switch (mCalibration.orientationCalibration) {
4178 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004179 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004180 break;
4181 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004182 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004183 break;
4184 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004185 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004186 break;
4187 default:
4188 ALOG_ASSERT(false);
4189 }
4190
4191 // Distance
4192 switch (mCalibration.distanceCalibration) {
4193 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 break;
4199 default:
4200 ALOG_ASSERT(false);
4201 }
4202
4203 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004205 mCalibration.distanceScale);
4206 }
4207
4208 switch (mCalibration.coverageCalibration) {
4209 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004210 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004211 break;
4212 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004213 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004214 break;
4215 default:
4216 ALOG_ASSERT(false);
4217 }
4218}
4219
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004220void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4221 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004222
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004223 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4224 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4225 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4226 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4227 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4228 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004229}
4230
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004231void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004232 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4233 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004234}
4235
Michael Wrightd02c5b62014-02-10 15:10:22 -08004236void TouchInputMapper::reset(nsecs_t when) {
4237 mCursorButtonAccumulator.reset(getDevice());
4238 mCursorScrollAccumulator.reset(getDevice());
4239 mTouchButtonAccumulator.reset(getDevice());
4240
4241 mPointerVelocityControl.reset();
4242 mWheelXVelocityControl.reset();
4243 mWheelYVelocityControl.reset();
4244
Michael Wright842500e2015-03-13 17:32:02 -07004245 mRawStatesPending.clear();
4246 mCurrentRawState.clear();
4247 mCurrentCookedState.clear();
4248 mLastRawState.clear();
4249 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004250 mPointerUsage = POINTER_USAGE_NONE;
4251 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004252 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004253 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004254 mDownTime = 0;
4255
4256 mCurrentVirtualKey.down = false;
4257
4258 mPointerGesture.reset();
4259 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004260 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004261
Yi Kong9b14ac62018-07-17 13:48:38 -07004262 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004263 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4264 mPointerController->clearSpots();
4265 }
4266
4267 InputMapper::reset(when);
4268}
4269
Michael Wright842500e2015-03-13 17:32:02 -07004270void TouchInputMapper::resetExternalStylus() {
4271 mExternalStylusState.clear();
4272 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004273 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004274 mExternalStylusDataPending = false;
4275}
4276
Michael Wright43fd19f2015-04-21 19:02:58 +01004277void TouchInputMapper::clearStylusDataPendingFlags() {
4278 mExternalStylusDataPending = false;
4279 mExternalStylusFusionTimeout = LLONG_MAX;
4280}
4281
Michael Wrightd02c5b62014-02-10 15:10:22 -08004282void TouchInputMapper::process(const RawEvent* rawEvent) {
4283 mCursorButtonAccumulator.process(rawEvent);
4284 mCursorScrollAccumulator.process(rawEvent);
4285 mTouchButtonAccumulator.process(rawEvent);
4286
4287 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4288 sync(rawEvent->when);
4289 }
4290}
4291
4292void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004293 const RawState* last = mRawStatesPending.isEmpty() ?
4294 &mCurrentRawState : &mRawStatesPending.top();
4295
4296 // Push a new state.
4297 mRawStatesPending.push();
4298 RawState* next = &mRawStatesPending.editTop();
4299 next->clear();
4300 next->when = when;
4301
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004303 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004304 | mCursorButtonAccumulator.getButtonState();
4305
Michael Wright842500e2015-03-13 17:32:02 -07004306 // Sync scroll
4307 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4308 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004309 mCursorScrollAccumulator.finishSync();
4310
Michael Wright842500e2015-03-13 17:32:02 -07004311 // Sync touch
4312 syncTouch(when, next);
4313
4314 // Assign pointer ids.
4315 if (!mHavePointerIds) {
4316 assignPointerIds(last, next);
4317 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318
4319#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004320 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4321 "hovering ids 0x%08x -> 0x%08x",
4322 last->rawPointerData.pointerCount,
4323 next->rawPointerData.pointerCount,
4324 last->rawPointerData.touchingIdBits.value,
4325 next->rawPointerData.touchingIdBits.value,
4326 last->rawPointerData.hoveringIdBits.value,
4327 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004328#endif
4329
Michael Wright842500e2015-03-13 17:32:02 -07004330 processRawTouches(false /*timeout*/);
4331}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004332
Michael Wright842500e2015-03-13 17:32:02 -07004333void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004334 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4335 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004336 mCurrentRawState.clear();
4337 mRawStatesPending.clear();
4338 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004339 }
4340
Michael Wright842500e2015-03-13 17:32:02 -07004341 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4342 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4343 // touching the current state will only observe the events that have been dispatched to the
4344 // rest of the pipeline.
4345 const size_t N = mRawStatesPending.size();
4346 size_t count;
4347 for(count = 0; count < N; count++) {
4348 const RawState& next = mRawStatesPending[count];
4349
4350 // A failure to assign the stylus id means that we're waiting on stylus data
4351 // and so should defer the rest of the pipeline.
4352 if (assignExternalStylusId(next, timeout)) {
4353 break;
4354 }
4355
4356 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004357 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004358 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004359 if (mCurrentRawState.when < mLastRawState.when) {
4360 mCurrentRawState.when = mLastRawState.when;
4361 }
Michael Wright842500e2015-03-13 17:32:02 -07004362 cookAndDispatch(mCurrentRawState.when);
4363 }
4364 if (count != 0) {
4365 mRawStatesPending.removeItemsAt(0, count);
4366 }
4367
Michael Wright842500e2015-03-13 17:32:02 -07004368 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004369 if (timeout) {
4370 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4371 clearStylusDataPendingFlags();
4372 mCurrentRawState.copyFrom(mLastRawState);
4373#if DEBUG_STYLUS_FUSION
4374 ALOGD("Timeout expired, synthesizing event with new stylus data");
4375#endif
4376 cookAndDispatch(when);
4377 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4378 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4379 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4380 }
Michael Wright842500e2015-03-13 17:32:02 -07004381 }
4382}
4383
4384void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4385 // Always start with a clean state.
4386 mCurrentCookedState.clear();
4387
4388 // Apply stylus buttons to current raw state.
4389 applyExternalStylusButtonState(when);
4390
4391 // Handle policy on initial down or hover events.
4392 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4393 && mCurrentRawState.rawPointerData.pointerCount != 0;
4394
4395 uint32_t policyFlags = 0;
4396 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4397 if (initialDown || buttonsPressed) {
4398 // If this is a touch screen, hide the pointer on an initial down.
4399 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4400 getContext()->fadePointer();
4401 }
4402
4403 if (mParameters.wake) {
4404 policyFlags |= POLICY_FLAG_WAKE;
4405 }
4406 }
4407
4408 // Consume raw off-screen touches before cooking pointer data.
4409 // If touches are consumed, subsequent code will not receive any pointer data.
4410 if (consumeRawTouches(when, policyFlags)) {
4411 mCurrentRawState.rawPointerData.clear();
4412 }
4413
4414 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4415 // with cooked pointer data that has the same ids and indices as the raw data.
4416 // The following code can use either the raw or cooked data, as needed.
4417 cookPointerData();
4418
4419 // Apply stylus pressure to current cooked state.
4420 applyExternalStylusTouchState(when);
4421
4422 // Synthesize key down from raw buttons if needed.
4423 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004424 mViewport.displayId, policyFlags,
4425 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004426
4427 // Dispatch the touches either directly or by translation through a pointer on screen.
4428 if (mDeviceMode == DEVICE_MODE_POINTER) {
4429 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4430 !idBits.isEmpty(); ) {
4431 uint32_t id = idBits.clearFirstMarkedBit();
4432 const RawPointerData::Pointer& pointer =
4433 mCurrentRawState.rawPointerData.pointerForId(id);
4434 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4435 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4436 mCurrentCookedState.stylusIdBits.markBit(id);
4437 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4438 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4439 mCurrentCookedState.fingerIdBits.markBit(id);
4440 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4441 mCurrentCookedState.mouseIdBits.markBit(id);
4442 }
4443 }
4444 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4445 !idBits.isEmpty(); ) {
4446 uint32_t id = idBits.clearFirstMarkedBit();
4447 const RawPointerData::Pointer& pointer =
4448 mCurrentRawState.rawPointerData.pointerForId(id);
4449 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4450 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4451 mCurrentCookedState.stylusIdBits.markBit(id);
4452 }
4453 }
4454
4455 // Stylus takes precedence over all tools, then mouse, then finger.
4456 PointerUsage pointerUsage = mPointerUsage;
4457 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4458 mCurrentCookedState.mouseIdBits.clear();
4459 mCurrentCookedState.fingerIdBits.clear();
4460 pointerUsage = POINTER_USAGE_STYLUS;
4461 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4462 mCurrentCookedState.fingerIdBits.clear();
4463 pointerUsage = POINTER_USAGE_MOUSE;
4464 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4465 isPointerDown(mCurrentRawState.buttonState)) {
4466 pointerUsage = POINTER_USAGE_GESTURES;
4467 }
4468
4469 dispatchPointerUsage(when, policyFlags, pointerUsage);
4470 } else {
4471 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004472 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004473 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4474 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4475
4476 mPointerController->setButtonState(mCurrentRawState.buttonState);
4477 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4478 mCurrentCookedState.cookedPointerData.idToIndex,
4479 mCurrentCookedState.cookedPointerData.touchingIdBits);
4480 }
4481
Michael Wright8e812822015-06-22 16:18:21 +01004482 if (!mCurrentMotionAborted) {
4483 dispatchButtonRelease(when, policyFlags);
4484 dispatchHoverExit(when, policyFlags);
4485 dispatchTouches(when, policyFlags);
4486 dispatchHoverEnterAndMove(when, policyFlags);
4487 dispatchButtonPress(when, policyFlags);
4488 }
4489
4490 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4491 mCurrentMotionAborted = false;
4492 }
Michael Wright842500e2015-03-13 17:32:02 -07004493 }
4494
4495 // Synthesize key up from raw buttons if needed.
4496 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004497 mViewport.displayId, policyFlags,
4498 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004499
4500 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004501 mCurrentRawState.rawVScroll = 0;
4502 mCurrentRawState.rawHScroll = 0;
4503
4504 // Copy current touch to last touch in preparation for the next cycle.
4505 mLastRawState.copyFrom(mCurrentRawState);
4506 mLastCookedState.copyFrom(mCurrentCookedState);
4507}
4508
4509void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004510 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004511 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4512 }
4513}
4514
4515void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004516 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4517 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004518
Michael Wright53dca3a2015-04-23 17:39:53 +01004519 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4520 float pressure = mExternalStylusState.pressure;
4521 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4522 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4523 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4524 }
4525 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4526 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4527
4528 PointerProperties& properties =
4529 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004530 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4531 properties.toolType = mExternalStylusState.toolType;
4532 }
4533 }
4534}
4535
4536bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4537 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4538 return false;
4539 }
4540
4541 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4542 && state.rawPointerData.pointerCount != 0;
4543 if (initialDown) {
4544 if (mExternalStylusState.pressure != 0.0f) {
4545#if DEBUG_STYLUS_FUSION
4546 ALOGD("Have both stylus and touch data, beginning fusion");
4547#endif
4548 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4549 } else if (timeout) {
4550#if DEBUG_STYLUS_FUSION
4551 ALOGD("Timeout expired, assuming touch is not a stylus.");
4552#endif
4553 resetExternalStylus();
4554 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004555 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4556 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004557 }
4558#if DEBUG_STYLUS_FUSION
4559 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004560 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004561#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004562 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004563 return true;
4564 }
4565 }
4566
4567 // Check if the stylus pointer has gone up.
4568 if (mExternalStylusId != -1 &&
4569 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4570#if DEBUG_STYLUS_FUSION
4571 ALOGD("Stylus pointer is going up");
4572#endif
4573 mExternalStylusId = -1;
4574 }
4575
4576 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004577}
4578
4579void TouchInputMapper::timeoutExpired(nsecs_t when) {
4580 if (mDeviceMode == DEVICE_MODE_POINTER) {
4581 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4582 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4583 }
Michael Wright842500e2015-03-13 17:32:02 -07004584 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004585 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004586 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004587 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4588 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004589 }
4590 }
4591}
4592
4593void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004594 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004595 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004596 // We're either in the middle of a fused stream of data or we're waiting on data before
4597 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4598 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004599 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004600 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004601 }
4602}
4603
4604bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4605 // Check for release of a virtual key.
4606 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004607 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004608 // Pointer went up while virtual key was down.
4609 mCurrentVirtualKey.down = false;
4610 if (!mCurrentVirtualKey.ignored) {
4611#if DEBUG_VIRTUAL_KEYS
4612 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4613 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4614#endif
4615 dispatchVirtualKey(when, policyFlags,
4616 AKEY_EVENT_ACTION_UP,
4617 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4618 }
4619 return true;
4620 }
4621
Michael Wright842500e2015-03-13 17:32:02 -07004622 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4623 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4624 const RawPointerData::Pointer& pointer =
4625 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004626 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4627 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4628 // Pointer is still within the space of the virtual key.
4629 return true;
4630 }
4631 }
4632
4633 // Pointer left virtual key area or another pointer also went down.
4634 // Send key cancellation but do not consume the touch yet.
4635 // This is useful when the user swipes through from the virtual key area
4636 // into the main display surface.
4637 mCurrentVirtualKey.down = false;
4638 if (!mCurrentVirtualKey.ignored) {
4639#if DEBUG_VIRTUAL_KEYS
4640 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4641 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4642#endif
4643 dispatchVirtualKey(when, policyFlags,
4644 AKEY_EVENT_ACTION_UP,
4645 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4646 | AKEY_EVENT_FLAG_CANCELED);
4647 }
4648 }
4649
Michael Wright842500e2015-03-13 17:32:02 -07004650 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4651 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004652 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004653 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4654 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004655 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4656 // If exactly one pointer went down, check for virtual key hit.
4657 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004658 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004659 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4660 if (virtualKey) {
4661 mCurrentVirtualKey.down = true;
4662 mCurrentVirtualKey.downTime = when;
4663 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4664 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4665 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4666 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4667
4668 if (!mCurrentVirtualKey.ignored) {
4669#if DEBUG_VIRTUAL_KEYS
4670 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4671 mCurrentVirtualKey.keyCode,
4672 mCurrentVirtualKey.scanCode);
4673#endif
4674 dispatchVirtualKey(when, policyFlags,
4675 AKEY_EVENT_ACTION_DOWN,
4676 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4677 }
4678 }
4679 }
4680 return true;
4681 }
4682 }
4683
4684 // Disable all virtual key touches that happen within a short time interval of the
4685 // most recent touch within the screen area. The idea is to filter out stray
4686 // virtual key presses when interacting with the touch screen.
4687 //
4688 // Problems we're trying to solve:
4689 //
4690 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4691 // virtual key area that is implemented by a separate touch panel and accidentally
4692 // triggers a virtual key.
4693 //
4694 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4695 // area and accidentally triggers a virtual key. This often happens when virtual keys
4696 // are layed out below the screen near to where the on screen keyboard's space bar
4697 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004698 if (mConfig.virtualKeyQuietTime > 0 &&
4699 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004700 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4701 }
4702 return false;
4703}
4704
4705void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4706 int32_t keyEventAction, int32_t keyEventFlags) {
4707 int32_t keyCode = mCurrentVirtualKey.keyCode;
4708 int32_t scanCode = mCurrentVirtualKey.scanCode;
4709 nsecs_t downTime = mCurrentVirtualKey.downTime;
4710 int32_t metaState = mContext->getGlobalMetaState();
4711 policyFlags |= POLICY_FLAG_VIRTUAL;
4712
Prabir Pradhan42611e02018-11-27 14:04:02 -08004713 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
4714 mViewport.displayId,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004715 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004716 getListener()->notifyKey(&args);
4717}
4718
Michael Wright8e812822015-06-22 16:18:21 +01004719void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4720 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4721 if (!currentIdBits.isEmpty()) {
4722 int32_t metaState = getContext()->getGlobalMetaState();
4723 int32_t buttonState = mCurrentCookedState.buttonState;
4724 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4725 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004726 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004727 mCurrentCookedState.cookedPointerData.pointerProperties,
4728 mCurrentCookedState.cookedPointerData.pointerCoords,
4729 mCurrentCookedState.cookedPointerData.idToIndex,
4730 currentIdBits, -1,
4731 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4732 mCurrentMotionAborted = true;
4733 }
4734}
4735
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004737 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4738 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004739 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004740 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741
4742 if (currentIdBits == lastIdBits) {
4743 if (!currentIdBits.isEmpty()) {
4744 // No pointer id changes so this is a move event.
4745 // The listener takes care of batching moves so we don't have to deal with that here.
4746 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004747 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004748 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004749 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004750 mCurrentCookedState.cookedPointerData.pointerProperties,
4751 mCurrentCookedState.cookedPointerData.pointerCoords,
4752 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004753 currentIdBits, -1,
4754 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4755 }
4756 } else {
4757 // There may be pointers going up and pointers going down and pointers moving
4758 // all at the same time.
4759 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4760 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4761 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4762 BitSet32 dispatchedIdBits(lastIdBits.value);
4763
4764 // Update last coordinates of pointers that have moved so that we observe the new
4765 // pointer positions at the same time as other pointers that have just gone up.
4766 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004767 mCurrentCookedState.cookedPointerData.pointerProperties,
4768 mCurrentCookedState.cookedPointerData.pointerCoords,
4769 mCurrentCookedState.cookedPointerData.idToIndex,
4770 mLastCookedState.cookedPointerData.pointerProperties,
4771 mLastCookedState.cookedPointerData.pointerCoords,
4772 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004773 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004774 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004775 moveNeeded = true;
4776 }
4777
4778 // Dispatch pointer up events.
4779 while (!upIdBits.isEmpty()) {
4780 uint32_t upId = upIdBits.clearFirstMarkedBit();
4781
4782 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004783 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004784 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004785 mLastCookedState.cookedPointerData.pointerProperties,
4786 mLastCookedState.cookedPointerData.pointerCoords,
4787 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004788 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004789 dispatchedIdBits.clearBit(upId);
4790 }
4791
4792 // Dispatch move events if any of the remaining pointers moved from their old locations.
4793 // Although applications receive new locations as part of individual pointer up
4794 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004795 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004796 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4797 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004798 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004799 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004800 mCurrentCookedState.cookedPointerData.pointerProperties,
4801 mCurrentCookedState.cookedPointerData.pointerCoords,
4802 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004803 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004804 }
4805
4806 // Dispatch pointer down events using the new pointer locations.
4807 while (!downIdBits.isEmpty()) {
4808 uint32_t downId = downIdBits.clearFirstMarkedBit();
4809 dispatchedIdBits.markBit(downId);
4810
4811 if (dispatchedIdBits.count() == 1) {
4812 // First pointer is going down. Set down time.
4813 mDownTime = when;
4814 }
4815
4816 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004817 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004818 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004819 mCurrentCookedState.cookedPointerData.pointerProperties,
4820 mCurrentCookedState.cookedPointerData.pointerCoords,
4821 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004822 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004823 }
4824 }
4825}
4826
4827void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4828 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004829 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4830 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 int32_t metaState = getContext()->getGlobalMetaState();
4832 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004833 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004834 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004835 mLastCookedState.cookedPointerData.pointerProperties,
4836 mLastCookedState.cookedPointerData.pointerCoords,
4837 mLastCookedState.cookedPointerData.idToIndex,
4838 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4840 mSentHoverEnter = false;
4841 }
4842}
4843
4844void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004845 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4846 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 int32_t metaState = getContext()->getGlobalMetaState();
4848 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004849 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004850 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004851 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004852 mCurrentCookedState.cookedPointerData.pointerProperties,
4853 mCurrentCookedState.cookedPointerData.pointerCoords,
4854 mCurrentCookedState.cookedPointerData.idToIndex,
4855 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004856 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4857 mSentHoverEnter = true;
4858 }
4859
4860 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004861 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004862 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004863 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004864 mCurrentCookedState.cookedPointerData.pointerProperties,
4865 mCurrentCookedState.cookedPointerData.pointerCoords,
4866 mCurrentCookedState.cookedPointerData.idToIndex,
4867 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004868 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4869 }
4870}
4871
Michael Wright7b159c92015-05-14 14:48:03 +01004872void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4873 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4874 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4875 const int32_t metaState = getContext()->getGlobalMetaState();
4876 int32_t buttonState = mLastCookedState.buttonState;
4877 while (!releasedButtons.isEmpty()) {
4878 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4879 buttonState &= ~actionButton;
4880 dispatchMotion(when, policyFlags, mSource,
4881 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4882 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004883 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004884 mCurrentCookedState.cookedPointerData.pointerProperties,
4885 mCurrentCookedState.cookedPointerData.pointerCoords,
4886 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4887 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4888 }
4889}
4890
4891void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4892 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4893 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4894 const int32_t metaState = getContext()->getGlobalMetaState();
4895 int32_t buttonState = mLastCookedState.buttonState;
4896 while (!pressedButtons.isEmpty()) {
4897 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4898 buttonState |= actionButton;
4899 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4900 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004901 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004902 mCurrentCookedState.cookedPointerData.pointerProperties,
4903 mCurrentCookedState.cookedPointerData.pointerCoords,
4904 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4905 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4906 }
4907}
4908
4909const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4910 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4911 return cookedPointerData.touchingIdBits;
4912 }
4913 return cookedPointerData.hoveringIdBits;
4914}
4915
Michael Wrightd02c5b62014-02-10 15:10:22 -08004916void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004917 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004918
Michael Wright842500e2015-03-13 17:32:02 -07004919 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004920 mCurrentCookedState.deviceTimestamp =
4921 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004922 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4923 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4924 mCurrentRawState.rawPointerData.hoveringIdBits;
4925 mCurrentCookedState.cookedPointerData.touchingIdBits =
4926 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004927
Michael Wright7b159c92015-05-14 14:48:03 +01004928 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4929 mCurrentCookedState.buttonState = 0;
4930 } else {
4931 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4932 }
4933
Michael Wrightd02c5b62014-02-10 15:10:22 -08004934 // Walk through the the active pointers and map device coordinates onto
4935 // surface coordinates and adjust for display orientation.
4936 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004937 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004938
4939 // Size
4940 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4941 switch (mCalibration.sizeCalibration) {
4942 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4943 case Calibration::SIZE_CALIBRATION_DIAMETER:
4944 case Calibration::SIZE_CALIBRATION_BOX:
4945 case Calibration::SIZE_CALIBRATION_AREA:
4946 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4947 touchMajor = in.touchMajor;
4948 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4949 toolMajor = in.toolMajor;
4950 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4951 size = mRawPointerAxes.touchMinor.valid
4952 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4953 } else if (mRawPointerAxes.touchMajor.valid) {
4954 toolMajor = touchMajor = in.touchMajor;
4955 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4956 ? in.touchMinor : in.touchMajor;
4957 size = mRawPointerAxes.touchMinor.valid
4958 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4959 } else if (mRawPointerAxes.toolMajor.valid) {
4960 touchMajor = toolMajor = in.toolMajor;
4961 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4962 ? in.toolMinor : in.toolMajor;
4963 size = mRawPointerAxes.toolMinor.valid
4964 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4965 } else {
4966 ALOG_ASSERT(false, "No touch or tool axes. "
4967 "Size calibration should have been resolved to NONE.");
4968 touchMajor = 0;
4969 touchMinor = 0;
4970 toolMajor = 0;
4971 toolMinor = 0;
4972 size = 0;
4973 }
4974
4975 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004976 uint32_t touchingCount =
4977 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004978 if (touchingCount > 1) {
4979 touchMajor /= touchingCount;
4980 touchMinor /= touchingCount;
4981 toolMajor /= touchingCount;
4982 toolMinor /= touchingCount;
4983 size /= touchingCount;
4984 }
4985 }
4986
4987 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4988 touchMajor *= mGeometricScale;
4989 touchMinor *= mGeometricScale;
4990 toolMajor *= mGeometricScale;
4991 toolMinor *= mGeometricScale;
4992 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4993 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4994 touchMinor = touchMajor;
4995 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4996 toolMinor = toolMajor;
4997 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4998 touchMinor = touchMajor;
4999 toolMinor = toolMajor;
5000 }
5001
5002 mCalibration.applySizeScaleAndBias(&touchMajor);
5003 mCalibration.applySizeScaleAndBias(&touchMinor);
5004 mCalibration.applySizeScaleAndBias(&toolMajor);
5005 mCalibration.applySizeScaleAndBias(&toolMinor);
5006 size *= mSizeScale;
5007 break;
5008 default:
5009 touchMajor = 0;
5010 touchMinor = 0;
5011 toolMajor = 0;
5012 toolMinor = 0;
5013 size = 0;
5014 break;
5015 }
5016
5017 // Pressure
5018 float pressure;
5019 switch (mCalibration.pressureCalibration) {
5020 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5021 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5022 pressure = in.pressure * mPressureScale;
5023 break;
5024 default:
5025 pressure = in.isHovering ? 0 : 1;
5026 break;
5027 }
5028
5029 // Tilt and Orientation
5030 float tilt;
5031 float orientation;
5032 if (mHaveTilt) {
5033 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5034 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5035 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5036 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5037 } else {
5038 tilt = 0;
5039
5040 switch (mCalibration.orientationCalibration) {
5041 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5042 orientation = in.orientation * mOrientationScale;
5043 break;
5044 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5045 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5046 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5047 if (c1 != 0 || c2 != 0) {
5048 orientation = atan2f(c1, c2) * 0.5f;
5049 float confidence = hypotf(c1, c2);
5050 float scale = 1.0f + confidence / 16.0f;
5051 touchMajor *= scale;
5052 touchMinor /= scale;
5053 toolMajor *= scale;
5054 toolMinor /= scale;
5055 } else {
5056 orientation = 0;
5057 }
5058 break;
5059 }
5060 default:
5061 orientation = 0;
5062 }
5063 }
5064
5065 // Distance
5066 float distance;
5067 switch (mCalibration.distanceCalibration) {
5068 case Calibration::DISTANCE_CALIBRATION_SCALED:
5069 distance = in.distance * mDistanceScale;
5070 break;
5071 default:
5072 distance = 0;
5073 }
5074
5075 // Coverage
5076 int32_t rawLeft, rawTop, rawRight, rawBottom;
5077 switch (mCalibration.coverageCalibration) {
5078 case Calibration::COVERAGE_CALIBRATION_BOX:
5079 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5080 rawRight = in.toolMinor & 0x0000ffff;
5081 rawBottom = in.toolMajor & 0x0000ffff;
5082 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5083 break;
5084 default:
5085 rawLeft = rawTop = rawRight = rawBottom = 0;
5086 break;
5087 }
5088
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005089 // Adjust X,Y coords for device calibration
5090 // TODO: Adjust coverage coords?
5091 float xTransformed = in.x, yTransformed = in.y;
5092 mAffineTransform.applyTo(xTransformed, yTransformed);
5093
5094 // Adjust X, Y, and coverage coords for surface orientation.
5095 float x, y;
5096 float left, top, right, bottom;
5097
Michael Wrightd02c5b62014-02-10 15:10:22 -08005098 switch (mSurfaceOrientation) {
5099 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005100 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5101 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005102 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5103 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5104 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5105 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5106 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005107 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005108 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5109 }
5110 break;
5111 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005112 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005113 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005114 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5115 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005116 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5117 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5118 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005119 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005120 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5121 }
5122 break;
5123 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005124 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005125 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005126 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5127 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005128 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5129 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5130 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005131 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005132 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5133 }
5134 break;
5135 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005136 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5137 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005138 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5139 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5140 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5141 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5142 break;
5143 }
5144
5145 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005146 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005147 out.clear();
5148 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5149 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5150 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5151 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5152 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5153 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5155 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5156 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5157 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5158 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5159 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5160 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5161 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5162 } else {
5163 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5164 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5165 }
5166
5167 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005168 PointerProperties& properties =
5169 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005170 uint32_t id = in.id;
5171 properties.clear();
5172 properties.id = id;
5173 properties.toolType = in.toolType;
5174
5175 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005176 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005177 }
5178}
5179
5180void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5181 PointerUsage pointerUsage) {
5182 if (pointerUsage != mPointerUsage) {
5183 abortPointerUsage(when, policyFlags);
5184 mPointerUsage = pointerUsage;
5185 }
5186
5187 switch (mPointerUsage) {
5188 case POINTER_USAGE_GESTURES:
5189 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5190 break;
5191 case POINTER_USAGE_STYLUS:
5192 dispatchPointerStylus(when, policyFlags);
5193 break;
5194 case POINTER_USAGE_MOUSE:
5195 dispatchPointerMouse(when, policyFlags);
5196 break;
5197 default:
5198 break;
5199 }
5200}
5201
5202void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5203 switch (mPointerUsage) {
5204 case POINTER_USAGE_GESTURES:
5205 abortPointerGestures(when, policyFlags);
5206 break;
5207 case POINTER_USAGE_STYLUS:
5208 abortPointerStylus(when, policyFlags);
5209 break;
5210 case POINTER_USAGE_MOUSE:
5211 abortPointerMouse(when, policyFlags);
5212 break;
5213 default:
5214 break;
5215 }
5216
5217 mPointerUsage = POINTER_USAGE_NONE;
5218}
5219
5220void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5221 bool isTimeout) {
5222 // Update current gesture coordinates.
5223 bool cancelPreviousGesture, finishPreviousGesture;
5224 bool sendEvents = preparePointerGestures(when,
5225 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5226 if (!sendEvents) {
5227 return;
5228 }
5229 if (finishPreviousGesture) {
5230 cancelPreviousGesture = false;
5231 }
5232
5233 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005234 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5235 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005236 if (finishPreviousGesture || cancelPreviousGesture) {
5237 mPointerController->clearSpots();
5238 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005239
5240 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5241 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5242 mPointerGesture.currentGestureIdToIndex,
5243 mPointerGesture.currentGestureIdBits);
5244 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005245 } else {
5246 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5247 }
5248
5249 // Show or hide the pointer if needed.
5250 switch (mPointerGesture.currentGestureMode) {
5251 case PointerGesture::NEUTRAL:
5252 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005253 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5254 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005255 // Remind the user of where the pointer is after finishing a gesture with spots.
5256 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5257 }
5258 break;
5259 case PointerGesture::TAP:
5260 case PointerGesture::TAP_DRAG:
5261 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5262 case PointerGesture::HOVER:
5263 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005264 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005265 // Unfade the pointer when the current gesture manipulates the
5266 // area directly under the pointer.
5267 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5268 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005269 case PointerGesture::FREEFORM:
5270 // Fade the pointer when the current gesture manipulates a different
5271 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005272 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5274 } else {
5275 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5276 }
5277 break;
5278 }
5279
5280 // Send events!
5281 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005282 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005283
5284 // Update last coordinates of pointers that have moved so that we observe the new
5285 // pointer positions at the same time as other pointers that have just gone up.
5286 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5287 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5288 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5289 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5290 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5291 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5292 bool moveNeeded = false;
5293 if (down && !cancelPreviousGesture && !finishPreviousGesture
5294 && !mPointerGesture.lastGestureIdBits.isEmpty()
5295 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5296 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5297 & mPointerGesture.lastGestureIdBits.value);
5298 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5299 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5300 mPointerGesture.lastGestureProperties,
5301 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5302 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005303 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005304 moveNeeded = true;
5305 }
5306 }
5307
5308 // Send motion events for all pointers that went up or were canceled.
5309 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5310 if (!dispatchedGestureIdBits.isEmpty()) {
5311 if (cancelPreviousGesture) {
5312 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005313 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005314 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005315 mPointerGesture.lastGestureProperties,
5316 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005317 dispatchedGestureIdBits, -1, 0,
5318 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319
5320 dispatchedGestureIdBits.clear();
5321 } else {
5322 BitSet32 upGestureIdBits;
5323 if (finishPreviousGesture) {
5324 upGestureIdBits = dispatchedGestureIdBits;
5325 } else {
5326 upGestureIdBits.value = dispatchedGestureIdBits.value
5327 & ~mPointerGesture.currentGestureIdBits.value;
5328 }
5329 while (!upGestureIdBits.isEmpty()) {
5330 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5331
5332 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005333 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005335 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005336 mPointerGesture.lastGestureProperties,
5337 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5338 dispatchedGestureIdBits, id,
5339 0, 0, mPointerGesture.downTime);
5340
5341 dispatchedGestureIdBits.clearBit(id);
5342 }
5343 }
5344 }
5345
5346 // Send motion events for all pointers that moved.
5347 if (moveNeeded) {
5348 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005349 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005350 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005351 mPointerGesture.currentGestureProperties,
5352 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5353 dispatchedGestureIdBits, -1,
5354 0, 0, mPointerGesture.downTime);
5355 }
5356
5357 // Send motion events for all pointers that went down.
5358 if (down) {
5359 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5360 & ~dispatchedGestureIdBits.value);
5361 while (!downGestureIdBits.isEmpty()) {
5362 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5363 dispatchedGestureIdBits.markBit(id);
5364
5365 if (dispatchedGestureIdBits.count() == 1) {
5366 mPointerGesture.downTime = when;
5367 }
5368
5369 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005370 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005371 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005372 mPointerGesture.currentGestureProperties,
5373 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5374 dispatchedGestureIdBits, id,
5375 0, 0, mPointerGesture.downTime);
5376 }
5377 }
5378
5379 // Send motion events for hover.
5380 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5381 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005382 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005383 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005384 mPointerGesture.currentGestureProperties,
5385 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5386 mPointerGesture.currentGestureIdBits, -1,
5387 0, 0, mPointerGesture.downTime);
5388 } else if (dispatchedGestureIdBits.isEmpty()
5389 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5390 // Synthesize a hover move event after all pointers go up to indicate that
5391 // the pointer is hovering again even if the user is not currently touching
5392 // the touch pad. This ensures that a view will receive a fresh hover enter
5393 // event after a tap.
5394 float x, y;
5395 mPointerController->getPosition(&x, &y);
5396
5397 PointerProperties pointerProperties;
5398 pointerProperties.clear();
5399 pointerProperties.id = 0;
5400 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5401
5402 PointerCoords pointerCoords;
5403 pointerCoords.clear();
5404 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5405 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5406
Dan Harmsaca28402018-12-17 13:55:20 -08005407 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
5408 mSource, mViewport.displayId, policyFlags,
5409 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005410 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005411 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08005412 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005413 getListener()->notifyMotion(&args);
5414 }
5415
5416 // Update state.
5417 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5418 if (!down) {
5419 mPointerGesture.lastGestureIdBits.clear();
5420 } else {
5421 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5422 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5423 uint32_t id = idBits.clearFirstMarkedBit();
5424 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5425 mPointerGesture.lastGestureProperties[index].copyFrom(
5426 mPointerGesture.currentGestureProperties[index]);
5427 mPointerGesture.lastGestureCoords[index].copyFrom(
5428 mPointerGesture.currentGestureCoords[index]);
5429 mPointerGesture.lastGestureIdToIndex[id] = index;
5430 }
5431 }
5432}
5433
5434void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5435 // Cancel previously dispatches pointers.
5436 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5437 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005438 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005440 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005441 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 mPointerGesture.lastGestureProperties,
5443 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5444 mPointerGesture.lastGestureIdBits, -1,
5445 0, 0, mPointerGesture.downTime);
5446 }
5447
5448 // Reset the current pointer gesture.
5449 mPointerGesture.reset();
5450 mPointerVelocityControl.reset();
5451
5452 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005453 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005454 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5455 mPointerController->clearSpots();
5456 }
5457}
5458
5459bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5460 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5461 *outCancelPreviousGesture = false;
5462 *outFinishPreviousGesture = false;
5463
5464 // Handle TAP timeout.
5465 if (isTimeout) {
5466#if DEBUG_GESTURES
5467 ALOGD("Gestures: Processing timeout");
5468#endif
5469
5470 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5471 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5472 // The tap/drag timeout has not yet expired.
5473 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5474 + mConfig.pointerGestureTapDragInterval);
5475 } else {
5476 // The tap is finished.
5477#if DEBUG_GESTURES
5478 ALOGD("Gestures: TAP finished");
5479#endif
5480 *outFinishPreviousGesture = true;
5481
5482 mPointerGesture.activeGestureId = -1;
5483 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5484 mPointerGesture.currentGestureIdBits.clear();
5485
5486 mPointerVelocityControl.reset();
5487 return true;
5488 }
5489 }
5490
5491 // We did not handle this timeout.
5492 return false;
5493 }
5494
Michael Wright842500e2015-03-13 17:32:02 -07005495 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5496 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497
5498 // Update the velocity tracker.
5499 {
5500 VelocityTracker::Position positions[MAX_POINTERS];
5501 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005502 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005503 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005504 const RawPointerData::Pointer& pointer =
5505 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005506 positions[count].x = pointer.x * mPointerXMovementScale;
5507 positions[count].y = pointer.y * mPointerYMovementScale;
5508 }
5509 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005510 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005511 }
5512
5513 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5514 // to NEUTRAL, then we should not generate tap event.
5515 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5516 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5517 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5518 mPointerGesture.resetTap();
5519 }
5520
5521 // Pick a new active touch id if needed.
5522 // Choose an arbitrary pointer that just went down, if there is one.
5523 // Otherwise choose an arbitrary remaining pointer.
5524 // This guarantees we always have an active touch id when there is at least one pointer.
5525 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5527 int32_t activeTouchId = lastActiveTouchId;
5528 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005529 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005531 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 mPointerGesture.firstTouchTime = when;
5533 }
Michael Wright842500e2015-03-13 17:32:02 -07005534 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005535 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005536 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005537 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005538 } else {
5539 activeTouchId = mPointerGesture.activeTouchId = -1;
5540 }
5541 }
5542
5543 // Determine whether we are in quiet time.
5544 bool isQuietTime = false;
5545 if (activeTouchId < 0) {
5546 mPointerGesture.resetQuietTime();
5547 } else {
5548 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5549 if (!isQuietTime) {
5550 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5551 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5552 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5553 && currentFingerCount < 2) {
5554 // Enter quiet time when exiting swipe or freeform state.
5555 // This is to prevent accidentally entering the hover state and flinging the
5556 // pointer when finishing a swipe and there is still one pointer left onscreen.
5557 isQuietTime = true;
5558 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5559 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005560 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005561 // Enter quiet time when releasing the button and there are still two or more
5562 // fingers down. This may indicate that one finger was used to press the button
5563 // but it has not gone up yet.
5564 isQuietTime = true;
5565 }
5566 if (isQuietTime) {
5567 mPointerGesture.quietTime = when;
5568 }
5569 }
5570 }
5571
5572 // Switch states based on button and pointer state.
5573 if (isQuietTime) {
5574 // Case 1: Quiet time. (QUIET)
5575#if DEBUG_GESTURES
5576 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5577 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5578#endif
5579 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5580 *outFinishPreviousGesture = true;
5581 }
5582
5583 mPointerGesture.activeGestureId = -1;
5584 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5585 mPointerGesture.currentGestureIdBits.clear();
5586
5587 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005588 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005589 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5590 // The pointer follows the active touch point.
5591 // Emit DOWN, MOVE, UP events at the pointer location.
5592 //
5593 // Only the active touch matters; other fingers are ignored. This policy helps
5594 // to handle the case where the user places a second finger on the touch pad
5595 // to apply the necessary force to depress an integrated button below the surface.
5596 // We don't want the second finger to be delivered to applications.
5597 //
5598 // For this to work well, we need to make sure to track the pointer that is really
5599 // active. If the user first puts one finger down to click then adds another
5600 // finger to drag then the active pointer should switch to the finger that is
5601 // being dragged.
5602#if DEBUG_GESTURES
5603 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5604 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5605#endif
5606 // Reset state when just starting.
5607 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5608 *outFinishPreviousGesture = true;
5609 mPointerGesture.activeGestureId = 0;
5610 }
5611
5612 // Switch pointers if needed.
5613 // Find the fastest pointer and follow it.
5614 if (activeTouchId >= 0 && currentFingerCount > 1) {
5615 int32_t bestId = -1;
5616 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005617 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005618 uint32_t id = idBits.clearFirstMarkedBit();
5619 float vx, vy;
5620 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5621 float speed = hypotf(vx, vy);
5622 if (speed > bestSpeed) {
5623 bestId = id;
5624 bestSpeed = speed;
5625 }
5626 }
5627 }
5628 if (bestId >= 0 && bestId != activeTouchId) {
5629 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005630#if DEBUG_GESTURES
5631 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5632 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5633#endif
5634 }
5635 }
5636
Jun Mukaifa1706a2015-12-03 01:14:46 -08005637 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005638 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005639 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005640 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005641 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005642 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005643 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5644 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005645
5646 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5647 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5648
5649 // Move the pointer using a relative motion.
5650 // When using spots, the click will occur at the position of the anchor
5651 // spot and all other spots will move there.
5652 mPointerController->move(deltaX, deltaY);
5653 } else {
5654 mPointerVelocityControl.reset();
5655 }
5656
5657 float x, y;
5658 mPointerController->getPosition(&x, &y);
5659
5660 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5661 mPointerGesture.currentGestureIdBits.clear();
5662 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5663 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5664 mPointerGesture.currentGestureProperties[0].clear();
5665 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5666 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5667 mPointerGesture.currentGestureCoords[0].clear();
5668 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5669 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5670 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5671 } else if (currentFingerCount == 0) {
5672 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5673 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5674 *outFinishPreviousGesture = true;
5675 }
5676
5677 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5678 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5679 bool tapped = false;
5680 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5681 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5682 && lastFingerCount == 1) {
5683 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5684 float x, y;
5685 mPointerController->getPosition(&x, &y);
5686 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5687 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5688#if DEBUG_GESTURES
5689 ALOGD("Gestures: TAP");
5690#endif
5691
5692 mPointerGesture.tapUpTime = when;
5693 getContext()->requestTimeoutAtTime(when
5694 + mConfig.pointerGestureTapDragInterval);
5695
5696 mPointerGesture.activeGestureId = 0;
5697 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5698 mPointerGesture.currentGestureIdBits.clear();
5699 mPointerGesture.currentGestureIdBits.markBit(
5700 mPointerGesture.activeGestureId);
5701 mPointerGesture.currentGestureIdToIndex[
5702 mPointerGesture.activeGestureId] = 0;
5703 mPointerGesture.currentGestureProperties[0].clear();
5704 mPointerGesture.currentGestureProperties[0].id =
5705 mPointerGesture.activeGestureId;
5706 mPointerGesture.currentGestureProperties[0].toolType =
5707 AMOTION_EVENT_TOOL_TYPE_FINGER;
5708 mPointerGesture.currentGestureCoords[0].clear();
5709 mPointerGesture.currentGestureCoords[0].setAxisValue(
5710 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5711 mPointerGesture.currentGestureCoords[0].setAxisValue(
5712 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5713 mPointerGesture.currentGestureCoords[0].setAxisValue(
5714 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5715
5716 tapped = true;
5717 } else {
5718#if DEBUG_GESTURES
5719 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5720 x - mPointerGesture.tapX,
5721 y - mPointerGesture.tapY);
5722#endif
5723 }
5724 } else {
5725#if DEBUG_GESTURES
5726 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5727 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5728 (when - mPointerGesture.tapDownTime) * 0.000001f);
5729 } else {
5730 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5731 }
5732#endif
5733 }
5734 }
5735
5736 mPointerVelocityControl.reset();
5737
5738 if (!tapped) {
5739#if DEBUG_GESTURES
5740 ALOGD("Gestures: NEUTRAL");
5741#endif
5742 mPointerGesture.activeGestureId = -1;
5743 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5744 mPointerGesture.currentGestureIdBits.clear();
5745 }
5746 } else if (currentFingerCount == 1) {
5747 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5748 // The pointer follows the active touch point.
5749 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5750 // When in TAP_DRAG, emit MOVE events at the pointer location.
5751 ALOG_ASSERT(activeTouchId >= 0);
5752
5753 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5754 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5755 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5756 float x, y;
5757 mPointerController->getPosition(&x, &y);
5758 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5759 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5760 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5761 } else {
5762#if DEBUG_GESTURES
5763 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5764 x - mPointerGesture.tapX,
5765 y - mPointerGesture.tapY);
5766#endif
5767 }
5768 } else {
5769#if DEBUG_GESTURES
5770 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5771 (when - mPointerGesture.tapUpTime) * 0.000001f);
5772#endif
5773 }
5774 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5775 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5776 }
5777
Jun Mukaifa1706a2015-12-03 01:14:46 -08005778 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005779 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005780 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005781 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005782 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005783 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005784 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5785 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005786
5787 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5788 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5789
5790 // Move the pointer using a relative motion.
5791 // When using spots, the hover or drag will occur at the position of the anchor spot.
5792 mPointerController->move(deltaX, deltaY);
5793 } else {
5794 mPointerVelocityControl.reset();
5795 }
5796
5797 bool down;
5798 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5799#if DEBUG_GESTURES
5800 ALOGD("Gestures: TAP_DRAG");
5801#endif
5802 down = true;
5803 } else {
5804#if DEBUG_GESTURES
5805 ALOGD("Gestures: HOVER");
5806#endif
5807 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5808 *outFinishPreviousGesture = true;
5809 }
5810 mPointerGesture.activeGestureId = 0;
5811 down = false;
5812 }
5813
5814 float x, y;
5815 mPointerController->getPosition(&x, &y);
5816
5817 mPointerGesture.currentGestureIdBits.clear();
5818 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5819 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5820 mPointerGesture.currentGestureProperties[0].clear();
5821 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5822 mPointerGesture.currentGestureProperties[0].toolType =
5823 AMOTION_EVENT_TOOL_TYPE_FINGER;
5824 mPointerGesture.currentGestureCoords[0].clear();
5825 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5826 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5827 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5828 down ? 1.0f : 0.0f);
5829
5830 if (lastFingerCount == 0 && currentFingerCount != 0) {
5831 mPointerGesture.resetTap();
5832 mPointerGesture.tapDownTime = when;
5833 mPointerGesture.tapX = x;
5834 mPointerGesture.tapY = y;
5835 }
5836 } else {
5837 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5838 // We need to provide feedback for each finger that goes down so we cannot wait
5839 // for the fingers to move before deciding what to do.
5840 //
5841 // The ambiguous case is deciding what to do when there are two fingers down but they
5842 // have not moved enough to determine whether they are part of a drag or part of a
5843 // freeform gesture, or just a press or long-press at the pointer location.
5844 //
5845 // When there are two fingers we start with the PRESS hypothesis and we generate a
5846 // down at the pointer location.
5847 //
5848 // When the two fingers move enough or when additional fingers are added, we make
5849 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5850 ALOG_ASSERT(activeTouchId >= 0);
5851
5852 bool settled = when >= mPointerGesture.firstTouchTime
5853 + mConfig.pointerGestureMultitouchSettleInterval;
5854 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5855 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5856 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5857 *outFinishPreviousGesture = true;
5858 } else if (!settled && currentFingerCount > lastFingerCount) {
5859 // Additional pointers have gone down but not yet settled.
5860 // Reset the gesture.
5861#if DEBUG_GESTURES
5862 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5863 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5864 + mConfig.pointerGestureMultitouchSettleInterval - when)
5865 * 0.000001f);
5866#endif
5867 *outCancelPreviousGesture = true;
5868 } else {
5869 // Continue previous gesture.
5870 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5871 }
5872
5873 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5874 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5875 mPointerGesture.activeGestureId = 0;
5876 mPointerGesture.referenceIdBits.clear();
5877 mPointerVelocityControl.reset();
5878
5879 // Use the centroid and pointer location as the reference points for the gesture.
5880#if DEBUG_GESTURES
5881 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5882 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5883 + mConfig.pointerGestureMultitouchSettleInterval - when)
5884 * 0.000001f);
5885#endif
Michael Wright842500e2015-03-13 17:32:02 -07005886 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887 &mPointerGesture.referenceTouchX,
5888 &mPointerGesture.referenceTouchY);
5889 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5890 &mPointerGesture.referenceGestureY);
5891 }
5892
5893 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005894 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005895 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5896 uint32_t id = idBits.clearFirstMarkedBit();
5897 mPointerGesture.referenceDeltas[id].dx = 0;
5898 mPointerGesture.referenceDeltas[id].dy = 0;
5899 }
Michael Wright842500e2015-03-13 17:32:02 -07005900 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005901
5902 // Add delta for all fingers and calculate a common movement delta.
5903 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005904 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5905 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005906 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5907 bool first = (idBits == commonIdBits);
5908 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005909 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5910 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005911 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5912 delta.dx += cpd.x - lpd.x;
5913 delta.dy += cpd.y - lpd.y;
5914
5915 if (first) {
5916 commonDeltaX = delta.dx;
5917 commonDeltaY = delta.dy;
5918 } else {
5919 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5920 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5921 }
5922 }
5923
5924 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5925 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5926 float dist[MAX_POINTER_ID + 1];
5927 int32_t distOverThreshold = 0;
5928 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5929 uint32_t id = idBits.clearFirstMarkedBit();
5930 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5931 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5932 delta.dy * mPointerYZoomScale);
5933 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5934 distOverThreshold += 1;
5935 }
5936 }
5937
5938 // Only transition when at least two pointers have moved further than
5939 // the minimum distance threshold.
5940 if (distOverThreshold >= 2) {
5941 if (currentFingerCount > 2) {
5942 // There are more than two pointers, switch to FREEFORM.
5943#if DEBUG_GESTURES
5944 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5945 currentFingerCount);
5946#endif
5947 *outCancelPreviousGesture = true;
5948 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5949 } else {
5950 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005951 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005952 uint32_t id1 = idBits.clearFirstMarkedBit();
5953 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005954 const RawPointerData::Pointer& p1 =
5955 mCurrentRawState.rawPointerData.pointerForId(id1);
5956 const RawPointerData::Pointer& p2 =
5957 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005958 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5959 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5960 // There are two pointers but they are too far apart for a SWIPE,
5961 // switch to FREEFORM.
5962#if DEBUG_GESTURES
5963 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5964 mutualDistance, mPointerGestureMaxSwipeWidth);
5965#endif
5966 *outCancelPreviousGesture = true;
5967 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5968 } else {
5969 // There are two pointers. Wait for both pointers to start moving
5970 // before deciding whether this is a SWIPE or FREEFORM gesture.
5971 float dist1 = dist[id1];
5972 float dist2 = dist[id2];
5973 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5974 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5975 // Calculate the dot product of the displacement vectors.
5976 // When the vectors are oriented in approximately the same direction,
5977 // the angle betweeen them is near zero and the cosine of the angle
5978 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5979 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5980 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5981 float dx1 = delta1.dx * mPointerXZoomScale;
5982 float dy1 = delta1.dy * mPointerYZoomScale;
5983 float dx2 = delta2.dx * mPointerXZoomScale;
5984 float dy2 = delta2.dy * mPointerYZoomScale;
5985 float dot = dx1 * dx2 + dy1 * dy2;
5986 float cosine = dot / (dist1 * dist2); // denominator always > 0
5987 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5988 // Pointers are moving in the same direction. Switch to SWIPE.
5989#if DEBUG_GESTURES
5990 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5991 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5992 "cosine %0.3f >= %0.3f",
5993 dist1, mConfig.pointerGestureMultitouchMinDistance,
5994 dist2, mConfig.pointerGestureMultitouchMinDistance,
5995 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5996#endif
5997 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5998 } else {
5999 // Pointers are moving in different directions. Switch to FREEFORM.
6000#if DEBUG_GESTURES
6001 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
6002 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
6003 "cosine %0.3f < %0.3f",
6004 dist1, mConfig.pointerGestureMultitouchMinDistance,
6005 dist2, mConfig.pointerGestureMultitouchMinDistance,
6006 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
6007#endif
6008 *outCancelPreviousGesture = true;
6009 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6010 }
6011 }
6012 }
6013 }
6014 }
6015 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6016 // Switch from SWIPE to FREEFORM if additional pointers go down.
6017 // Cancel previous gesture.
6018 if (currentFingerCount > 2) {
6019#if DEBUG_GESTURES
6020 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6021 currentFingerCount);
6022#endif
6023 *outCancelPreviousGesture = true;
6024 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6025 }
6026 }
6027
6028 // Move the reference points based on the overall group motion of the fingers
6029 // except in PRESS mode while waiting for a transition to occur.
6030 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6031 && (commonDeltaX || commonDeltaY)) {
6032 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6033 uint32_t id = idBits.clearFirstMarkedBit();
6034 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6035 delta.dx = 0;
6036 delta.dy = 0;
6037 }
6038
6039 mPointerGesture.referenceTouchX += commonDeltaX;
6040 mPointerGesture.referenceTouchY += commonDeltaY;
6041
6042 commonDeltaX *= mPointerXMovementScale;
6043 commonDeltaY *= mPointerYMovementScale;
6044
6045 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6046 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6047
6048 mPointerGesture.referenceGestureX += commonDeltaX;
6049 mPointerGesture.referenceGestureY += commonDeltaY;
6050 }
6051
6052 // Report gestures.
6053 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6054 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6055 // PRESS or SWIPE mode.
6056#if DEBUG_GESTURES
6057 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6058 "activeGestureId=%d, currentTouchPointerCount=%d",
6059 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6060#endif
6061 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6062
6063 mPointerGesture.currentGestureIdBits.clear();
6064 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6065 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6066 mPointerGesture.currentGestureProperties[0].clear();
6067 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6068 mPointerGesture.currentGestureProperties[0].toolType =
6069 AMOTION_EVENT_TOOL_TYPE_FINGER;
6070 mPointerGesture.currentGestureCoords[0].clear();
6071 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6072 mPointerGesture.referenceGestureX);
6073 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6074 mPointerGesture.referenceGestureY);
6075 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6076 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6077 // FREEFORM mode.
6078#if DEBUG_GESTURES
6079 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6080 "activeGestureId=%d, currentTouchPointerCount=%d",
6081 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6082#endif
6083 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6084
6085 mPointerGesture.currentGestureIdBits.clear();
6086
6087 BitSet32 mappedTouchIdBits;
6088 BitSet32 usedGestureIdBits;
6089 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6090 // Initially, assign the active gesture id to the active touch point
6091 // if there is one. No other touch id bits are mapped yet.
6092 if (!*outCancelPreviousGesture) {
6093 mappedTouchIdBits.markBit(activeTouchId);
6094 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6095 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6096 mPointerGesture.activeGestureId;
6097 } else {
6098 mPointerGesture.activeGestureId = -1;
6099 }
6100 } else {
6101 // Otherwise, assume we mapped all touches from the previous frame.
6102 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006103 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6104 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006105 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6106
6107 // Check whether we need to choose a new active gesture id because the
6108 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006109 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6110 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006111 !upTouchIdBits.isEmpty(); ) {
6112 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6113 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6114 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6115 mPointerGesture.activeGestureId = -1;
6116 break;
6117 }
6118 }
6119 }
6120
6121#if DEBUG_GESTURES
6122 ALOGD("Gestures: FREEFORM follow up "
6123 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6124 "activeGestureId=%d",
6125 mappedTouchIdBits.value, usedGestureIdBits.value,
6126 mPointerGesture.activeGestureId);
6127#endif
6128
Michael Wright842500e2015-03-13 17:32:02 -07006129 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130 for (uint32_t i = 0; i < currentFingerCount; i++) {
6131 uint32_t touchId = idBits.clearFirstMarkedBit();
6132 uint32_t gestureId;
6133 if (!mappedTouchIdBits.hasBit(touchId)) {
6134 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6135 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6136#if DEBUG_GESTURES
6137 ALOGD("Gestures: FREEFORM "
6138 "new mapping for touch id %d -> gesture id %d",
6139 touchId, gestureId);
6140#endif
6141 } else {
6142 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6143#if DEBUG_GESTURES
6144 ALOGD("Gestures: FREEFORM "
6145 "existing mapping for touch id %d -> gesture id %d",
6146 touchId, gestureId);
6147#endif
6148 }
6149 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6150 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6151
6152 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006153 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006154 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6155 * mPointerXZoomScale;
6156 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6157 * mPointerYZoomScale;
6158 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6159
6160 mPointerGesture.currentGestureProperties[i].clear();
6161 mPointerGesture.currentGestureProperties[i].id = gestureId;
6162 mPointerGesture.currentGestureProperties[i].toolType =
6163 AMOTION_EVENT_TOOL_TYPE_FINGER;
6164 mPointerGesture.currentGestureCoords[i].clear();
6165 mPointerGesture.currentGestureCoords[i].setAxisValue(
6166 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6167 mPointerGesture.currentGestureCoords[i].setAxisValue(
6168 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6169 mPointerGesture.currentGestureCoords[i].setAxisValue(
6170 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6171 }
6172
6173 if (mPointerGesture.activeGestureId < 0) {
6174 mPointerGesture.activeGestureId =
6175 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6176#if DEBUG_GESTURES
6177 ALOGD("Gestures: FREEFORM new "
6178 "activeGestureId=%d", mPointerGesture.activeGestureId);
6179#endif
6180 }
6181 }
6182 }
6183
Michael Wright842500e2015-03-13 17:32:02 -07006184 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185
6186#if DEBUG_GESTURES
6187 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6188 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6189 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6190 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6191 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6192 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6193 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6194 uint32_t id = idBits.clearFirstMarkedBit();
6195 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6196 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6197 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6198 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6199 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6200 id, index, properties.toolType,
6201 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6202 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6203 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6204 }
6205 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6206 uint32_t id = idBits.clearFirstMarkedBit();
6207 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6208 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6209 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6210 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6211 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6212 id, index, properties.toolType,
6213 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6214 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6215 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6216 }
6217#endif
6218 return true;
6219}
6220
6221void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6222 mPointerSimple.currentCoords.clear();
6223 mPointerSimple.currentProperties.clear();
6224
6225 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006226 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6227 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6228 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6229 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6230 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006231 mPointerController->setPosition(x, y);
6232
Michael Wright842500e2015-03-13 17:32:02 -07006233 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006234 down = !hovering;
6235
6236 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006237 mPointerSimple.currentCoords.copyFrom(
6238 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006239 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6240 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6241 mPointerSimple.currentProperties.id = 0;
6242 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006243 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006244 } else {
6245 down = false;
6246 hovering = false;
6247 }
6248
6249 dispatchPointerSimple(when, policyFlags, down, hovering);
6250}
6251
6252void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6253 abortPointerSimple(when, policyFlags);
6254}
6255
6256void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6257 mPointerSimple.currentCoords.clear();
6258 mPointerSimple.currentProperties.clear();
6259
6260 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006261 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6262 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6263 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006264 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006265 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6266 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006267 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006268 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006269 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006270 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006271 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272 * mPointerYMovementScale;
6273
6274 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6275 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6276
6277 mPointerController->move(deltaX, deltaY);
6278 } else {
6279 mPointerVelocityControl.reset();
6280 }
6281
Michael Wright842500e2015-03-13 17:32:02 -07006282 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 hovering = !down;
6284
6285 float x, y;
6286 mPointerController->getPosition(&x, &y);
6287 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006288 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006289 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6290 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6291 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6292 hovering ? 0.0f : 1.0f);
6293 mPointerSimple.currentProperties.id = 0;
6294 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006295 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006296 } else {
6297 mPointerVelocityControl.reset();
6298
6299 down = false;
6300 hovering = false;
6301 }
6302
6303 dispatchPointerSimple(when, policyFlags, down, hovering);
6304}
6305
6306void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6307 abortPointerSimple(when, policyFlags);
6308
6309 mPointerVelocityControl.reset();
6310}
6311
6312void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6313 bool down, bool hovering) {
6314 int32_t metaState = getContext()->getGlobalMetaState();
6315
Yi Kong9b14ac62018-07-17 13:48:38 -07006316 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006317 if (down || hovering) {
6318 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6319 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006320 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006321 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6322 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6323 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6324 }
6325 }
6326
6327 if (mPointerSimple.down && !down) {
6328 mPointerSimple.down = false;
6329
6330 // Send up.
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006331 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Dan Harmsaca28402018-12-17 13:55:20 -08006332 mSource, mViewport.displayId, policyFlags,
6333 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
6334 /* deviceTimestamp */ 0,
6335 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6336 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006337 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006338 getListener()->notifyMotion(&args);
6339 }
6340
6341 if (mPointerSimple.hovering && !hovering) {
6342 mPointerSimple.hovering = false;
6343
6344 // Send hover exit.
Dan Harmsaca28402018-12-17 13:55:20 -08006345 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6346 mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006347 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006348 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006349 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6350 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006351 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006352 getListener()->notifyMotion(&args);
6353 }
6354
6355 if (down) {
6356 if (!mPointerSimple.down) {
6357 mPointerSimple.down = true;
6358 mPointerSimple.downTime = when;
6359
6360 // Send down.
Dan Harmsaca28402018-12-17 13:55:20 -08006361 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6362 mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006363 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006364 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006365 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6366 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006367 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006368 getListener()->notifyMotion(&args);
6369 }
6370
6371 // Send move.
Dan Harmsaca28402018-12-17 13:55:20 -08006372 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6373 mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006374 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006375 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006376 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6377 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006378 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006379 getListener()->notifyMotion(&args);
6380 }
6381
6382 if (hovering) {
6383 if (!mPointerSimple.hovering) {
6384 mPointerSimple.hovering = true;
6385
6386 // Send hover enter.
Dan Harmsaca28402018-12-17 13:55:20 -08006387 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6388 mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006389 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006390 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006391 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006392 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6393 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006394 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006395 getListener()->notifyMotion(&args);
6396 }
6397
6398 // Send hover move.
Dan Harmsaca28402018-12-17 13:55:20 -08006399 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6400 mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006401 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006402 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006403 /* 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
Michael Wright842500e2015-03-13 17:32:02 -07006410 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6411 float vscroll = mCurrentRawState.rawVScroll;
6412 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006413 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6414 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006415
6416 // Send scroll.
6417 PointerCoords pointerCoords;
6418 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6419 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6420 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6421
Dan Harmsaca28402018-12-17 13:55:20 -08006422 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
6423 mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006424 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006425 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426 1, &mPointerSimple.currentProperties, &pointerCoords,
6427 mOrientedXPrecision, mOrientedYPrecision,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08006428 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006429 getListener()->notifyMotion(&args);
6430 }
6431
6432 // Save state.
6433 if (down || hovering) {
6434 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6435 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6436 } else {
6437 mPointerSimple.reset();
6438 }
6439}
6440
6441void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6442 mPointerSimple.currentCoords.clear();
6443 mPointerSimple.currentProperties.clear();
6444
6445 dispatchPointerSimple(when, policyFlags, false, false);
6446}
6447
6448void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006449 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006450 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006451 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006452 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6453 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006454 PointerCoords pointerCoords[MAX_POINTERS];
6455 PointerProperties pointerProperties[MAX_POINTERS];
6456 uint32_t pointerCount = 0;
6457 while (!idBits.isEmpty()) {
6458 uint32_t id = idBits.clearFirstMarkedBit();
6459 uint32_t index = idToIndex[id];
6460 pointerProperties[pointerCount].copyFrom(properties[index]);
6461 pointerCoords[pointerCount].copyFrom(coords[index]);
6462
6463 if (changedId >= 0 && id == uint32_t(changedId)) {
6464 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6465 }
6466
6467 pointerCount += 1;
6468 }
6469
6470 ALOG_ASSERT(pointerCount != 0);
6471
6472 if (changedId >= 0 && pointerCount == 1) {
6473 // Replace initial down and final up action.
6474 // We can compare the action without masking off the changed pointer index
6475 // because we know the index is 0.
6476 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6477 action = AMOTION_EVENT_ACTION_DOWN;
6478 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6479 action = AMOTION_EVENT_ACTION_UP;
6480 } else {
6481 // Can't happen.
6482 ALOG_ASSERT(false);
6483 }
6484 }
Dan Harmsaca28402018-12-17 13:55:20 -08006485
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006486 const int32_t deviceId = getDeviceId();
6487 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
6488 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId,
Dan Harmsaca28402018-12-17 13:55:20 -08006489 source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006490 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006491 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006492 xPrecision, yPrecision, downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006493 getListener()->notifyMotion(&args);
6494}
6495
6496bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6497 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6498 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6499 BitSet32 idBits) const {
6500 bool changed = false;
6501 while (!idBits.isEmpty()) {
6502 uint32_t id = idBits.clearFirstMarkedBit();
6503 uint32_t inIndex = inIdToIndex[id];
6504 uint32_t outIndex = outIdToIndex[id];
6505
6506 const PointerProperties& curInProperties = inProperties[inIndex];
6507 const PointerCoords& curInCoords = inCoords[inIndex];
6508 PointerProperties& curOutProperties = outProperties[outIndex];
6509 PointerCoords& curOutCoords = outCoords[outIndex];
6510
6511 if (curInProperties != curOutProperties) {
6512 curOutProperties.copyFrom(curInProperties);
6513 changed = true;
6514 }
6515
6516 if (curInCoords != curOutCoords) {
6517 curOutCoords.copyFrom(curInCoords);
6518 changed = true;
6519 }
6520 }
6521 return changed;
6522}
6523
6524void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006525 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006526 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6527 }
6528}
6529
Jeff Brownc9aa6282015-02-11 19:03:28 -08006530void TouchInputMapper::cancelTouch(nsecs_t when) {
6531 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006532 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006533}
6534
Michael Wrightd02c5b62014-02-10 15:10:22 -08006535bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006536 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006537 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006538 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006539 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6540 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6541 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542}
6543
6544const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6545 int32_t x, int32_t y) {
6546 size_t numVirtualKeys = mVirtualKeys.size();
6547 for (size_t i = 0; i < numVirtualKeys; i++) {
6548 const VirtualKey& virtualKey = mVirtualKeys[i];
6549
6550#if DEBUG_VIRTUAL_KEYS
6551 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6552 "left=%d, top=%d, right=%d, bottom=%d",
6553 x, y,
6554 virtualKey.keyCode, virtualKey.scanCode,
6555 virtualKey.hitLeft, virtualKey.hitTop,
6556 virtualKey.hitRight, virtualKey.hitBottom);
6557#endif
6558
6559 if (virtualKey.isHit(x, y)) {
6560 return & virtualKey;
6561 }
6562 }
6563
Yi Kong9b14ac62018-07-17 13:48:38 -07006564 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565}
6566
Michael Wright842500e2015-03-13 17:32:02 -07006567void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6568 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6569 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006570
Michael Wright842500e2015-03-13 17:32:02 -07006571 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006572
6573 if (currentPointerCount == 0) {
6574 // No pointers to assign.
6575 return;
6576 }
6577
6578 if (lastPointerCount == 0) {
6579 // All pointers are new.
6580 for (uint32_t i = 0; i < currentPointerCount; i++) {
6581 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006582 current->rawPointerData.pointers[i].id = id;
6583 current->rawPointerData.idToIndex[id] = i;
6584 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585 }
6586 return;
6587 }
6588
6589 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006590 && current->rawPointerData.pointers[0].toolType
6591 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006592 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006593 uint32_t id = last->rawPointerData.pointers[0].id;
6594 current->rawPointerData.pointers[0].id = id;
6595 current->rawPointerData.idToIndex[id] = 0;
6596 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006597 return;
6598 }
6599
6600 // General case.
6601 // We build a heap of squared euclidean distances between current and last pointers
6602 // associated with the current and last pointer indices. Then, we find the best
6603 // match (by distance) for each current pointer.
6604 // The pointers must have the same tool type but it is possible for them to
6605 // transition from hovering to touching or vice-versa while retaining the same id.
6606 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6607
6608 uint32_t heapSize = 0;
6609 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6610 currentPointerIndex++) {
6611 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6612 lastPointerIndex++) {
6613 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006614 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006615 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006616 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006617 if (currentPointer.toolType == lastPointer.toolType) {
6618 int64_t deltaX = currentPointer.x - lastPointer.x;
6619 int64_t deltaY = currentPointer.y - lastPointer.y;
6620
6621 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6622
6623 // Insert new element into the heap (sift up).
6624 heap[heapSize].currentPointerIndex = currentPointerIndex;
6625 heap[heapSize].lastPointerIndex = lastPointerIndex;
6626 heap[heapSize].distance = distance;
6627 heapSize += 1;
6628 }
6629 }
6630 }
6631
6632 // Heapify
6633 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6634 startIndex -= 1;
6635 for (uint32_t parentIndex = startIndex; ;) {
6636 uint32_t childIndex = parentIndex * 2 + 1;
6637 if (childIndex >= heapSize) {
6638 break;
6639 }
6640
6641 if (childIndex + 1 < heapSize
6642 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6643 childIndex += 1;
6644 }
6645
6646 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6647 break;
6648 }
6649
6650 swap(heap[parentIndex], heap[childIndex]);
6651 parentIndex = childIndex;
6652 }
6653 }
6654
6655#if DEBUG_POINTER_ASSIGNMENT
6656 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6657 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006658 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006659 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6660 heap[i].distance);
6661 }
6662#endif
6663
6664 // Pull matches out by increasing order of distance.
6665 // To avoid reassigning pointers that have already been matched, the loop keeps track
6666 // of which last and current pointers have been matched using the matchedXXXBits variables.
6667 // It also tracks the used pointer id bits.
6668 BitSet32 matchedLastBits(0);
6669 BitSet32 matchedCurrentBits(0);
6670 BitSet32 usedIdBits(0);
6671 bool first = true;
6672 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6673 while (heapSize > 0) {
6674 if (first) {
6675 // The first time through the loop, we just consume the root element of
6676 // the heap (the one with smallest distance).
6677 first = false;
6678 } else {
6679 // Previous iterations consumed the root element of the heap.
6680 // Pop root element off of the heap (sift down).
6681 heap[0] = heap[heapSize];
6682 for (uint32_t parentIndex = 0; ;) {
6683 uint32_t childIndex = parentIndex * 2 + 1;
6684 if (childIndex >= heapSize) {
6685 break;
6686 }
6687
6688 if (childIndex + 1 < heapSize
6689 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6690 childIndex += 1;
6691 }
6692
6693 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6694 break;
6695 }
6696
6697 swap(heap[parentIndex], heap[childIndex]);
6698 parentIndex = childIndex;
6699 }
6700
6701#if DEBUG_POINTER_ASSIGNMENT
6702 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6703 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006704 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006705 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6706 heap[i].distance);
6707 }
6708#endif
6709 }
6710
6711 heapSize -= 1;
6712
6713 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6714 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6715
6716 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6717 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6718
6719 matchedCurrentBits.markBit(currentPointerIndex);
6720 matchedLastBits.markBit(lastPointerIndex);
6721
Michael Wright842500e2015-03-13 17:32:02 -07006722 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6723 current->rawPointerData.pointers[currentPointerIndex].id = id;
6724 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6725 current->rawPointerData.markIdBit(id,
6726 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006727 usedIdBits.markBit(id);
6728
6729#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006730 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6731 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006732 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6733#endif
6734 break;
6735 }
6736 }
6737
6738 // Assign fresh ids to pointers that were not matched in the process.
6739 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6740 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6741 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6742
Michael Wright842500e2015-03-13 17:32:02 -07006743 current->rawPointerData.pointers[currentPointerIndex].id = id;
6744 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6745 current->rawPointerData.markIdBit(id,
6746 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006747
6748#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006749 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006750#endif
6751 }
6752}
6753
6754int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6755 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6756 return AKEY_STATE_VIRTUAL;
6757 }
6758
6759 size_t numVirtualKeys = mVirtualKeys.size();
6760 for (size_t i = 0; i < numVirtualKeys; i++) {
6761 const VirtualKey& virtualKey = mVirtualKeys[i];
6762 if (virtualKey.keyCode == keyCode) {
6763 return AKEY_STATE_UP;
6764 }
6765 }
6766
6767 return AKEY_STATE_UNKNOWN;
6768}
6769
6770int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6771 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6772 return AKEY_STATE_VIRTUAL;
6773 }
6774
6775 size_t numVirtualKeys = mVirtualKeys.size();
6776 for (size_t i = 0; i < numVirtualKeys; i++) {
6777 const VirtualKey& virtualKey = mVirtualKeys[i];
6778 if (virtualKey.scanCode == scanCode) {
6779 return AKEY_STATE_UP;
6780 }
6781 }
6782
6783 return AKEY_STATE_UNKNOWN;
6784}
6785
6786bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6787 const int32_t* keyCodes, uint8_t* outFlags) {
6788 size_t numVirtualKeys = mVirtualKeys.size();
6789 for (size_t i = 0; i < numVirtualKeys; i++) {
6790 const VirtualKey& virtualKey = mVirtualKeys[i];
6791
6792 for (size_t i = 0; i < numCodes; i++) {
6793 if (virtualKey.keyCode == keyCodes[i]) {
6794 outFlags[i] = 1;
6795 }
6796 }
6797 }
6798
6799 return true;
6800}
6801
6802
6803// --- SingleTouchInputMapper ---
6804
6805SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6806 TouchInputMapper(device) {
6807}
6808
6809SingleTouchInputMapper::~SingleTouchInputMapper() {
6810}
6811
6812void SingleTouchInputMapper::reset(nsecs_t when) {
6813 mSingleTouchMotionAccumulator.reset(getDevice());
6814
6815 TouchInputMapper::reset(when);
6816}
6817
6818void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6819 TouchInputMapper::process(rawEvent);
6820
6821 mSingleTouchMotionAccumulator.process(rawEvent);
6822}
6823
Michael Wright842500e2015-03-13 17:32:02 -07006824void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006825 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006826 outState->rawPointerData.pointerCount = 1;
6827 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006828
6829 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6830 && (mTouchButtonAccumulator.isHovering()
6831 || (mRawPointerAxes.pressure.valid
6832 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006833 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006834
Michael Wright842500e2015-03-13 17:32:02 -07006835 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006836 outPointer.id = 0;
6837 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6838 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6839 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6840 outPointer.touchMajor = 0;
6841 outPointer.touchMinor = 0;
6842 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6843 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6844 outPointer.orientation = 0;
6845 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6846 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6847 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6848 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6849 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6850 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6851 }
6852 outPointer.isHovering = isHovering;
6853 }
6854}
6855
6856void SingleTouchInputMapper::configureRawPointerAxes() {
6857 TouchInputMapper::configureRawPointerAxes();
6858
6859 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6860 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6861 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6862 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6863 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6864 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6865 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6866}
6867
6868bool SingleTouchInputMapper::hasStylus() const {
6869 return mTouchButtonAccumulator.hasStylus();
6870}
6871
6872
6873// --- MultiTouchInputMapper ---
6874
6875MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6876 TouchInputMapper(device) {
6877}
6878
6879MultiTouchInputMapper::~MultiTouchInputMapper() {
6880}
6881
6882void MultiTouchInputMapper::reset(nsecs_t when) {
6883 mMultiTouchMotionAccumulator.reset(getDevice());
6884
6885 mPointerIdBits.clear();
6886
6887 TouchInputMapper::reset(when);
6888}
6889
6890void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6891 TouchInputMapper::process(rawEvent);
6892
6893 mMultiTouchMotionAccumulator.process(rawEvent);
6894}
6895
Michael Wright842500e2015-03-13 17:32:02 -07006896void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006897 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6898 size_t outCount = 0;
6899 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006900 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006901
6902 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6903 const MultiTouchMotionAccumulator::Slot* inSlot =
6904 mMultiTouchMotionAccumulator.getSlot(inIndex);
6905 if (!inSlot->isInUse()) {
6906 continue;
6907 }
6908
6909 if (outCount >= MAX_POINTERS) {
6910#if DEBUG_POINTERS
6911 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6912 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006913 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006914#endif
6915 break; // too many fingers!
6916 }
6917
Michael Wright842500e2015-03-13 17:32:02 -07006918 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006919 outPointer.x = inSlot->getX();
6920 outPointer.y = inSlot->getY();
6921 outPointer.pressure = inSlot->getPressure();
6922 outPointer.touchMajor = inSlot->getTouchMajor();
6923 outPointer.touchMinor = inSlot->getTouchMinor();
6924 outPointer.toolMajor = inSlot->getToolMajor();
6925 outPointer.toolMinor = inSlot->getToolMinor();
6926 outPointer.orientation = inSlot->getOrientation();
6927 outPointer.distance = inSlot->getDistance();
6928 outPointer.tiltX = 0;
6929 outPointer.tiltY = 0;
6930
6931 outPointer.toolType = inSlot->getToolType();
6932 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6933 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6934 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6935 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6936 }
6937 }
6938
6939 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6940 && (mTouchButtonAccumulator.isHovering()
6941 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6942 outPointer.isHovering = isHovering;
6943
6944 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006945 if (mHavePointerIds) {
6946 int32_t trackingId = inSlot->getTrackingId();
6947 int32_t id = -1;
6948 if (trackingId >= 0) {
6949 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6950 uint32_t n = idBits.clearFirstMarkedBit();
6951 if (mPointerTrackingIdMap[n] == trackingId) {
6952 id = n;
6953 }
6954 }
6955
6956 if (id < 0 && !mPointerIdBits.isFull()) {
6957 id = mPointerIdBits.markFirstUnmarkedBit();
6958 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006959 }
Michael Wright842500e2015-03-13 17:32:02 -07006960 }
gaoshang1a632de2016-08-24 10:23:50 +08006961 if (id < 0) {
6962 mHavePointerIds = false;
6963 outState->rawPointerData.clearIdBits();
6964 newPointerIdBits.clear();
6965 } else {
6966 outPointer.id = id;
6967 outState->rawPointerData.idToIndex[id] = outCount;
6968 outState->rawPointerData.markIdBit(id, isHovering);
6969 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006970 }
Michael Wright842500e2015-03-13 17:32:02 -07006971 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006972 outCount += 1;
6973 }
6974
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006975 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006976 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006977 mPointerIdBits = newPointerIdBits;
6978
6979 mMultiTouchMotionAccumulator.finishSync();
6980}
6981
6982void MultiTouchInputMapper::configureRawPointerAxes() {
6983 TouchInputMapper::configureRawPointerAxes();
6984
6985 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6986 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6987 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6988 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6989 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6990 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6991 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6992 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6993 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6994 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6995 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6996
6997 if (mRawPointerAxes.trackingId.valid
6998 && mRawPointerAxes.slot.valid
6999 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
7000 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
7001 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007002 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
7003 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007004 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007005 slotCount = MAX_SLOTS;
7006 }
7007 mMultiTouchMotionAccumulator.configure(getDevice(),
7008 slotCount, true /*usingSlotsProtocol*/);
7009 } else {
7010 mMultiTouchMotionAccumulator.configure(getDevice(),
7011 MAX_POINTERS, false /*usingSlotsProtocol*/);
7012 }
7013}
7014
7015bool MultiTouchInputMapper::hasStylus() const {
7016 return mMultiTouchMotionAccumulator.hasStylus()
7017 || mTouchButtonAccumulator.hasStylus();
7018}
7019
Michael Wright842500e2015-03-13 17:32:02 -07007020// --- ExternalStylusInputMapper
7021
7022ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
7023 InputMapper(device) {
7024
7025}
7026
7027uint32_t ExternalStylusInputMapper::getSources() {
7028 return AINPUT_SOURCE_STYLUS;
7029}
7030
7031void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7032 InputMapper::populateDeviceInfo(info);
7033 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7034 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7035}
7036
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007037void ExternalStylusInputMapper::dump(std::string& dump) {
7038 dump += INDENT2 "External Stylus Input Mapper:\n";
7039 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007040 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007041 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007042 dumpStylusState(dump, mStylusState);
7043}
7044
7045void ExternalStylusInputMapper::configure(nsecs_t when,
7046 const InputReaderConfiguration* config, uint32_t changes) {
7047 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7048 mTouchButtonAccumulator.configure(getDevice());
7049}
7050
7051void ExternalStylusInputMapper::reset(nsecs_t when) {
7052 InputDevice* device = getDevice();
7053 mSingleTouchMotionAccumulator.reset(device);
7054 mTouchButtonAccumulator.reset(device);
7055 InputMapper::reset(when);
7056}
7057
7058void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7059 mSingleTouchMotionAccumulator.process(rawEvent);
7060 mTouchButtonAccumulator.process(rawEvent);
7061
7062 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7063 sync(rawEvent->when);
7064 }
7065}
7066
7067void ExternalStylusInputMapper::sync(nsecs_t when) {
7068 mStylusState.clear();
7069
7070 mStylusState.when = when;
7071
Michael Wright45ccacf2015-04-21 19:01:58 +01007072 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7073 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7074 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7075 }
7076
Michael Wright842500e2015-03-13 17:32:02 -07007077 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7078 if (mRawPressureAxis.valid) {
7079 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7080 } else if (mTouchButtonAccumulator.isToolActive()) {
7081 mStylusState.pressure = 1.0f;
7082 } else {
7083 mStylusState.pressure = 0.0f;
7084 }
7085
7086 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007087
7088 mContext->dispatchExternalStylusState(mStylusState);
7089}
7090
Michael Wrightd02c5b62014-02-10 15:10:22 -08007091
7092// --- JoystickInputMapper ---
7093
7094JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7095 InputMapper(device) {
7096}
7097
7098JoystickInputMapper::~JoystickInputMapper() {
7099}
7100
7101uint32_t JoystickInputMapper::getSources() {
7102 return AINPUT_SOURCE_JOYSTICK;
7103}
7104
7105void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7106 InputMapper::populateDeviceInfo(info);
7107
7108 for (size_t i = 0; i < mAxes.size(); i++) {
7109 const Axis& axis = mAxes.valueAt(i);
7110 addMotionRange(axis.axisInfo.axis, axis, info);
7111
7112 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7113 addMotionRange(axis.axisInfo.highAxis, axis, info);
7114
7115 }
7116 }
7117}
7118
7119void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7120 InputDeviceInfo* info) {
7121 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7122 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7123 /* In order to ease the transition for developers from using the old axes
7124 * to the newer, more semantically correct axes, we'll continue to register
7125 * the old axes as duplicates of their corresponding new ones. */
7126 int32_t compatAxis = getCompatAxis(axisId);
7127 if (compatAxis >= 0) {
7128 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7129 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7130 }
7131}
7132
7133/* A mapping from axes the joystick actually has to the axes that should be
7134 * artificially created for compatibility purposes.
7135 * Returns -1 if no compatibility axis is needed. */
7136int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7137 switch(axis) {
7138 case AMOTION_EVENT_AXIS_LTRIGGER:
7139 return AMOTION_EVENT_AXIS_BRAKE;
7140 case AMOTION_EVENT_AXIS_RTRIGGER:
7141 return AMOTION_EVENT_AXIS_GAS;
7142 }
7143 return -1;
7144}
7145
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007146void JoystickInputMapper::dump(std::string& dump) {
7147 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007148
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007149 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007150 size_t numAxes = mAxes.size();
7151 for (size_t i = 0; i < numAxes; i++) {
7152 const Axis& axis = mAxes.valueAt(i);
7153 const char* label = getAxisLabel(axis.axisInfo.axis);
7154 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007155 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007156 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007157 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007158 }
7159 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7160 label = getAxisLabel(axis.axisInfo.highAxis);
7161 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007162 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007163 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007164 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007165 axis.axisInfo.splitValue);
7166 }
7167 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007168 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007169 }
7170
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007171 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 -08007172 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007173 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007174 "highScale=%0.5f, highOffset=%0.5f\n",
7175 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007176 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007177 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7178 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7179 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7180 }
7181}
7182
7183void JoystickInputMapper::configure(nsecs_t when,
7184 const InputReaderConfiguration* config, uint32_t changes) {
7185 InputMapper::configure(when, config, changes);
7186
7187 if (!changes) { // first time only
7188 // Collect all axes.
7189 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7190 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7191 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7192 continue; // axis must be claimed by a different device
7193 }
7194
7195 RawAbsoluteAxisInfo rawAxisInfo;
7196 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7197 if (rawAxisInfo.valid) {
7198 // Map axis.
7199 AxisInfo axisInfo;
7200 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7201 if (!explicitlyMapped) {
7202 // Axis is not explicitly mapped, will choose a generic axis later.
7203 axisInfo.mode = AxisInfo::MODE_NORMAL;
7204 axisInfo.axis = -1;
7205 }
7206
7207 // Apply flat override.
7208 int32_t rawFlat = axisInfo.flatOverride < 0
7209 ? rawAxisInfo.flat : axisInfo.flatOverride;
7210
7211 // Calculate scaling factors and limits.
7212 Axis axis;
7213 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7214 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7215 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7216 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7217 scale, 0.0f, highScale, 0.0f,
7218 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7219 rawAxisInfo.resolution * scale);
7220 } else if (isCenteredAxis(axisInfo.axis)) {
7221 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7222 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7223 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7224 scale, offset, scale, offset,
7225 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7226 rawAxisInfo.resolution * scale);
7227 } else {
7228 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7229 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7230 scale, 0.0f, scale, 0.0f,
7231 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7232 rawAxisInfo.resolution * scale);
7233 }
7234
7235 // To eliminate noise while the joystick is at rest, filter out small variations
7236 // in axis values up front.
7237 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7238
7239 mAxes.add(abs, axis);
7240 }
7241 }
7242
7243 // If there are too many axes, start dropping them.
7244 // Prefer to keep explicitly mapped axes.
7245 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007246 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007247 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007248 pruneAxes(true);
7249 pruneAxes(false);
7250 }
7251
7252 // Assign generic axis ids to remaining axes.
7253 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7254 size_t numAxes = mAxes.size();
7255 for (size_t i = 0; i < numAxes; i++) {
7256 Axis& axis = mAxes.editValueAt(i);
7257 if (axis.axisInfo.axis < 0) {
7258 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7259 && haveAxis(nextGenericAxisId)) {
7260 nextGenericAxisId += 1;
7261 }
7262
7263 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7264 axis.axisInfo.axis = nextGenericAxisId;
7265 nextGenericAxisId += 1;
7266 } else {
7267 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7268 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007269 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007270 mAxes.removeItemsAt(i--);
7271 numAxes -= 1;
7272 }
7273 }
7274 }
7275 }
7276}
7277
7278bool JoystickInputMapper::haveAxis(int32_t axisId) {
7279 size_t numAxes = mAxes.size();
7280 for (size_t i = 0; i < numAxes; i++) {
7281 const Axis& axis = mAxes.valueAt(i);
7282 if (axis.axisInfo.axis == axisId
7283 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7284 && axis.axisInfo.highAxis == axisId)) {
7285 return true;
7286 }
7287 }
7288 return false;
7289}
7290
7291void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7292 size_t i = mAxes.size();
7293 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7294 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7295 continue;
7296 }
7297 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007298 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007299 mAxes.removeItemsAt(i);
7300 }
7301}
7302
7303bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7304 switch (axis) {
7305 case AMOTION_EVENT_AXIS_X:
7306 case AMOTION_EVENT_AXIS_Y:
7307 case AMOTION_EVENT_AXIS_Z:
7308 case AMOTION_EVENT_AXIS_RX:
7309 case AMOTION_EVENT_AXIS_RY:
7310 case AMOTION_EVENT_AXIS_RZ:
7311 case AMOTION_EVENT_AXIS_HAT_X:
7312 case AMOTION_EVENT_AXIS_HAT_Y:
7313 case AMOTION_EVENT_AXIS_ORIENTATION:
7314 case AMOTION_EVENT_AXIS_RUDDER:
7315 case AMOTION_EVENT_AXIS_WHEEL:
7316 return true;
7317 default:
7318 return false;
7319 }
7320}
7321
7322void JoystickInputMapper::reset(nsecs_t when) {
7323 // Recenter all axes.
7324 size_t numAxes = mAxes.size();
7325 for (size_t i = 0; i < numAxes; i++) {
7326 Axis& axis = mAxes.editValueAt(i);
7327 axis.resetValue();
7328 }
7329
7330 InputMapper::reset(when);
7331}
7332
7333void JoystickInputMapper::process(const RawEvent* rawEvent) {
7334 switch (rawEvent->type) {
7335 case EV_ABS: {
7336 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7337 if (index >= 0) {
7338 Axis& axis = mAxes.editValueAt(index);
7339 float newValue, highNewValue;
7340 switch (axis.axisInfo.mode) {
7341 case AxisInfo::MODE_INVERT:
7342 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7343 * axis.scale + axis.offset;
7344 highNewValue = 0.0f;
7345 break;
7346 case AxisInfo::MODE_SPLIT:
7347 if (rawEvent->value < axis.axisInfo.splitValue) {
7348 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7349 * axis.scale + axis.offset;
7350 highNewValue = 0.0f;
7351 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7352 newValue = 0.0f;
7353 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7354 * axis.highScale + axis.highOffset;
7355 } else {
7356 newValue = 0.0f;
7357 highNewValue = 0.0f;
7358 }
7359 break;
7360 default:
7361 newValue = rawEvent->value * axis.scale + axis.offset;
7362 highNewValue = 0.0f;
7363 break;
7364 }
7365 axis.newValue = newValue;
7366 axis.highNewValue = highNewValue;
7367 }
7368 break;
7369 }
7370
7371 case EV_SYN:
7372 switch (rawEvent->code) {
7373 case SYN_REPORT:
7374 sync(rawEvent->when, false /*force*/);
7375 break;
7376 }
7377 break;
7378 }
7379}
7380
7381void JoystickInputMapper::sync(nsecs_t when, bool force) {
7382 if (!filterAxes(force)) {
7383 return;
7384 }
7385
7386 int32_t metaState = mContext->getGlobalMetaState();
7387 int32_t buttonState = 0;
7388
7389 PointerProperties pointerProperties;
7390 pointerProperties.clear();
7391 pointerProperties.id = 0;
7392 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7393
7394 PointerCoords pointerCoords;
7395 pointerCoords.clear();
7396
7397 size_t numAxes = mAxes.size();
7398 for (size_t i = 0; i < numAxes; i++) {
7399 const Axis& axis = mAxes.valueAt(i);
7400 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7401 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7402 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7403 axis.highCurrentValue);
7404 }
7405 }
7406
7407 // Moving a joystick axis should not wake the device because joysticks can
7408 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7409 // button will likely wake the device.
7410 // TODO: Use the input device configuration to control this behavior more finely.
7411 uint32_t policyFlags = 0;
7412
Prabir Pradhan42611e02018-11-27 14:04:02 -08007413 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
7414 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007415 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007416 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou7b7c8f62018-12-12 16:09:20 -08007417 0, 0, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007418 getListener()->notifyMotion(&args);
7419}
7420
7421void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7422 int32_t axis, float value) {
7423 pointerCoords->setAxisValue(axis, value);
7424 /* In order to ease the transition for developers from using the old axes
7425 * to the newer, more semantically correct axes, we'll continue to produce
7426 * values for the old axes as mirrors of the value of their corresponding
7427 * new axes. */
7428 int32_t compatAxis = getCompatAxis(axis);
7429 if (compatAxis >= 0) {
7430 pointerCoords->setAxisValue(compatAxis, value);
7431 }
7432}
7433
7434bool JoystickInputMapper::filterAxes(bool force) {
7435 bool atLeastOneSignificantChange = force;
7436 size_t numAxes = mAxes.size();
7437 for (size_t i = 0; i < numAxes; i++) {
7438 Axis& axis = mAxes.editValueAt(i);
7439 if (force || hasValueChangedSignificantly(axis.filter,
7440 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7441 axis.currentValue = axis.newValue;
7442 atLeastOneSignificantChange = true;
7443 }
7444 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7445 if (force || hasValueChangedSignificantly(axis.filter,
7446 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7447 axis.highCurrentValue = axis.highNewValue;
7448 atLeastOneSignificantChange = true;
7449 }
7450 }
7451 }
7452 return atLeastOneSignificantChange;
7453}
7454
7455bool JoystickInputMapper::hasValueChangedSignificantly(
7456 float filter, float newValue, float currentValue, float min, float max) {
7457 if (newValue != currentValue) {
7458 // Filter out small changes in value unless the value is converging on the axis
7459 // bounds or center point. This is intended to reduce the amount of information
7460 // sent to applications by particularly noisy joysticks (such as PS3).
7461 if (fabs(newValue - currentValue) > filter
7462 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7463 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7464 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7465 return true;
7466 }
7467 }
7468 return false;
7469}
7470
7471bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7472 float filter, float newValue, float currentValue, float thresholdValue) {
7473 float newDistance = fabs(newValue - thresholdValue);
7474 if (newDistance < filter) {
7475 float oldDistance = fabs(currentValue - thresholdValue);
7476 if (newDistance < oldDistance) {
7477 return true;
7478 }
7479 }
7480 return false;
7481}
7482
7483} // namespace android