blob: 9e748d8975ef167db8357c57d5b58fd48125de5d [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))) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100239 NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800240 action, 0, keyCode, 0, context->getGlobalMetaState(), when);
241 context->getListener()->notifyKey(&args);
242 }
243}
244
245static void synthesizeButtonKeys(InputReaderContext* context, int32_t action,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100246 nsecs_t when, int32_t deviceId, uint32_t source, int32_t displayId,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800247 uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800249 lastButtonState, currentButtonState,
250 AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100251 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -0800252 lastButtonState, currentButtonState,
253 AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD);
254}
255
256
Jason Gereckeaf126fb2012-05-10 14:22:47 -0700257
Michael Wrightd02c5b62014-02-10 15:10:22 -0800258// --- InputReader ---
259
260InputReader::InputReader(const sp<EventHubInterface>& eventHub,
261 const sp<InputReaderPolicyInterface>& policy,
262 const sp<InputListenerInterface>& listener) :
263 mContext(this), mEventHub(eventHub), mPolicy(policy),
264 mGlobalMetaState(0), mGeneration(1),
265 mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
266 mConfigurationChangesToRefresh(0) {
267 mQueuedListener = new QueuedInputListener(listener);
268
269 { // acquire lock
270 AutoMutex _l(mLock);
271
272 refreshConfigurationLocked(0);
273 updateGlobalMetaStateLocked();
274 } // release lock
275}
276
277InputReader::~InputReader() {
278 for (size_t i = 0; i < mDevices.size(); i++) {
279 delete mDevices.valueAt(i);
280 }
281}
282
283void InputReader::loopOnce() {
284 int32_t oldGeneration;
285 int32_t timeoutMillis;
286 bool inputDevicesChanged = false;
287 Vector<InputDeviceInfo> inputDevices;
288 { // acquire lock
289 AutoMutex _l(mLock);
290
291 oldGeneration = mGeneration;
292 timeoutMillis = -1;
293
294 uint32_t changes = mConfigurationChangesToRefresh;
295 if (changes) {
296 mConfigurationChangesToRefresh = 0;
297 timeoutMillis = 0;
298 refreshConfigurationLocked(changes);
299 } else if (mNextTimeout != LLONG_MAX) {
300 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
301 timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);
302 }
303 } // release lock
304
305 size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
306
307 { // acquire lock
308 AutoMutex _l(mLock);
309 mReaderIsAliveCondition.broadcast();
310
311 if (count) {
312 processEventsLocked(mEventBuffer, count);
313 }
314
315 if (mNextTimeout != LLONG_MAX) {
316 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
317 if (now >= mNextTimeout) {
318#if DEBUG_RAW_EVENTS
319 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);
320#endif
321 mNextTimeout = LLONG_MAX;
322 timeoutExpiredLocked(now);
323 }
324 }
325
326 if (oldGeneration != mGeneration) {
327 inputDevicesChanged = true;
328 getInputDevicesLocked(inputDevices);
329 }
330 } // release lock
331
332 // Send out a message that the describes the changed input devices.
333 if (inputDevicesChanged) {
334 mPolicy->notifyInputDevicesChanged(inputDevices);
335 }
336
337 // Flush queued events out to the listener.
338 // This must happen outside of the lock because the listener could potentially call
339 // back into the InputReader's methods, such as getScanCodeState, or become blocked
340 // on another thread similarly waiting to acquire the InputReader lock thereby
341 // resulting in a deadlock. This situation is actually quite plausible because the
342 // listener is actually the input dispatcher, which calls into the window manager,
343 // which occasionally calls into the input reader.
344 mQueuedListener->flush();
345}
346
347void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {
348 for (const RawEvent* rawEvent = rawEvents; count;) {
349 int32_t type = rawEvent->type;
350 size_t batchSize = 1;
351 if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {
352 int32_t deviceId = rawEvent->deviceId;
353 while (batchSize < count) {
354 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT
355 || rawEvent[batchSize].deviceId != deviceId) {
356 break;
357 }
358 batchSize += 1;
359 }
360#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -0700361 ALOGD("BatchSize: %zu Count: %zu", batchSize, count);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800362#endif
363 processEventsForDeviceLocked(deviceId, rawEvent, batchSize);
364 } else {
365 switch (rawEvent->type) {
366 case EventHubInterface::DEVICE_ADDED:
367 addDeviceLocked(rawEvent->when, rawEvent->deviceId);
368 break;
369 case EventHubInterface::DEVICE_REMOVED:
370 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);
371 break;
372 case EventHubInterface::FINISHED_DEVICE_SCAN:
373 handleConfigurationChangedLocked(rawEvent->when);
374 break;
375 default:
376 ALOG_ASSERT(false); // can't happen
377 break;
378 }
379 }
380 count -= batchSize;
381 rawEvent += batchSize;
382 }
383}
384
385void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) {
386 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
387 if (deviceIndex >= 0) {
388 ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId);
389 return;
390 }
391
392 InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId);
393 uint32_t classes = mEventHub->getDeviceClasses(deviceId);
394 int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId);
395
396 InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes);
397 device->configure(when, &mConfig, 0);
398 device->reset(when);
399
400 if (device->isIgnored()) {
401 ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100402 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 } else {
404 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId,
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100405 identifier.name.c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800406 }
407
408 mDevices.add(deviceId, device);
409 bumpGenerationLocked();
Michael Wright842500e2015-03-13 17:32:02 -0700410
411 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
412 notifyExternalStylusPresenceChanged();
413 }
Michael Wrightd02c5b62014-02-10 15:10:22 -0800414}
415
416void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) {
Yi Kong9b14ac62018-07-17 13:48:38 -0700417 InputDevice* device = nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800418 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
419 if (deviceIndex < 0) {
420 ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId);
421 return;
422 }
423
424 device = mDevices.valueAt(deviceIndex);
425 mDevices.removeItemsAt(deviceIndex, 1);
426 bumpGenerationLocked();
427
428 if (device->isIgnored()) {
429 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100430 device->getId(), device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 } else {
432 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100433 device->getId(), device->getName().c_str(), device->getSources());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800434 }
435
Michael Wright842500e2015-03-13 17:32:02 -0700436 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
437 notifyExternalStylusPresenceChanged();
438 }
439
Michael Wrightd02c5b62014-02-10 15:10:22 -0800440 device->reset(when);
441 delete device;
442}
443
444InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber,
445 const InputDeviceIdentifier& identifier, uint32_t classes) {
446 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
447 controllerNumber, identifier, classes);
448
449 // External devices.
450 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
451 device->setExternal(true);
452 }
453
Tim Kilbourn063ff532015-04-08 10:26:18 -0700454 // Devices with mics.
455 if (classes & INPUT_DEVICE_CLASS_MIC) {
456 device->setMic(true);
457 }
458
Michael Wrightd02c5b62014-02-10 15:10:22 -0800459 // Switch-like devices.
460 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
461 device->addMapper(new SwitchInputMapper(device));
462 }
463
Prashant Malani1941ff52015-08-11 18:29:28 -0700464 // Scroll wheel-like devices.
465 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
466 device->addMapper(new RotaryEncoderInputMapper(device));
467 }
468
Michael Wrightd02c5b62014-02-10 15:10:22 -0800469 // Vibrator-like devices.
470 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
471 device->addMapper(new VibratorInputMapper(device));
472 }
473
474 // Keyboard-like devices.
475 uint32_t keyboardSource = 0;
476 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
477 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
478 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
479 }
480 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
481 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
482 }
483 if (classes & INPUT_DEVICE_CLASS_DPAD) {
484 keyboardSource |= AINPUT_SOURCE_DPAD;
485 }
486 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
487 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
488 }
489
490 if (keyboardSource != 0) {
491 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
492 }
493
494 // Cursor-like devices.
495 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
496 device->addMapper(new CursorInputMapper(device));
497 }
498
499 // Touchscreens and touchpad devices.
500 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
501 device->addMapper(new MultiTouchInputMapper(device));
502 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
503 device->addMapper(new SingleTouchInputMapper(device));
504 }
505
506 // Joystick-like devices.
507 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
508 device->addMapper(new JoystickInputMapper(device));
509 }
510
Michael Wright842500e2015-03-13 17:32:02 -0700511 // External stylus-like devices.
512 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
513 device->addMapper(new ExternalStylusInputMapper(device));
514 }
515
Michael Wrightd02c5b62014-02-10 15:10:22 -0800516 return device;
517}
518
519void InputReader::processEventsForDeviceLocked(int32_t deviceId,
520 const RawEvent* rawEvents, size_t count) {
521 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
522 if (deviceIndex < 0) {
523 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
524 return;
525 }
526
527 InputDevice* device = mDevices.valueAt(deviceIndex);
528 if (device->isIgnored()) {
529 //ALOGD("Discarding event for ignored deviceId %d.", deviceId);
530 return;
531 }
532
533 device->process(rawEvents, count);
534}
535
536void InputReader::timeoutExpiredLocked(nsecs_t when) {
537 for (size_t i = 0; i < mDevices.size(); i++) {
538 InputDevice* device = mDevices.valueAt(i);
539 if (!device->isIgnored()) {
540 device->timeoutExpired(when);
541 }
542 }
543}
544
545void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
546 // Reset global meta state because it depends on the list of all configured devices.
547 updateGlobalMetaStateLocked();
548
549 // Enqueue configuration changed.
550 NotifyConfigurationChangedArgs args(when);
551 mQueuedListener->notifyConfigurationChanged(&args);
552}
553
554void InputReader::refreshConfigurationLocked(uint32_t changes) {
555 mPolicy->getReaderConfiguration(&mConfig);
556 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
557
558 if (changes) {
559 ALOGI("Reconfiguring input devices. changes=0x%08x", changes);
560 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
561
562 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
563 mEventHub->requestReopenDevices();
564 } else {
565 for (size_t i = 0; i < mDevices.size(); i++) {
566 InputDevice* device = mDevices.valueAt(i);
567 device->configure(now, &mConfig, changes);
568 }
569 }
570 }
571}
572
573void InputReader::updateGlobalMetaStateLocked() {
574 mGlobalMetaState = 0;
575
576 for (size_t i = 0; i < mDevices.size(); i++) {
577 InputDevice* device = mDevices.valueAt(i);
578 mGlobalMetaState |= device->getMetaState();
579 }
580}
581
582int32_t InputReader::getGlobalMetaStateLocked() {
583 return mGlobalMetaState;
584}
585
Michael Wright842500e2015-03-13 17:32:02 -0700586void InputReader::notifyExternalStylusPresenceChanged() {
587 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
588}
589
590void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) {
591 for (size_t i = 0; i < mDevices.size(); i++) {
592 InputDevice* device = mDevices.valueAt(i);
593 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
594 outDevices.push();
595 device->getDeviceInfo(&outDevices.editTop());
596 }
597 }
598}
599
600void InputReader::dispatchExternalStylusState(const StylusState& state) {
601 for (size_t i = 0; i < mDevices.size(); i++) {
602 InputDevice* device = mDevices.valueAt(i);
603 device->updateExternalStylusState(state);
604 }
605}
606
Michael Wrightd02c5b62014-02-10 15:10:22 -0800607void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
608 mDisableVirtualKeysTimeout = time;
609}
610
611bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now,
612 InputDevice* device, int32_t keyCode, int32_t scanCode) {
613 if (now < mDisableVirtualKeysTimeout) {
614 ALOGI("Dropping virtual key from device %s because virtual keys are "
615 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100616 device->getName().c_str(),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800617 (mDisableVirtualKeysTimeout - now) * 0.000001,
618 keyCode, scanCode);
619 return true;
620 } else {
621 return false;
622 }
623}
624
625void InputReader::fadePointerLocked() {
626 for (size_t i = 0; i < mDevices.size(); i++) {
627 InputDevice* device = mDevices.valueAt(i);
628 device->fadePointer();
629 }
630}
631
632void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
633 if (when < mNextTimeout) {
634 mNextTimeout = when;
635 mEventHub->wake();
636 }
637}
638
639int32_t InputReader::bumpGenerationLocked() {
640 return ++mGeneration;
641}
642
643void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) {
644 AutoMutex _l(mLock);
645 getInputDevicesLocked(outInputDevices);
646}
647
648void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) {
649 outInputDevices.clear();
650
651 size_t numDevices = mDevices.size();
652 for (size_t i = 0; i < numDevices; i++) {
653 InputDevice* device = mDevices.valueAt(i);
654 if (!device->isIgnored()) {
655 outInputDevices.push();
656 device->getDeviceInfo(&outInputDevices.editTop());
657 }
658 }
659}
660
661int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask,
662 int32_t keyCode) {
663 AutoMutex _l(mLock);
664
665 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
666}
667
668int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask,
669 int32_t scanCode) {
670 AutoMutex _l(mLock);
671
672 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
673}
674
675int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
676 AutoMutex _l(mLock);
677
678 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
679}
680
681int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
682 GetStateFunc getStateFunc) {
683 int32_t result = AKEY_STATE_UNKNOWN;
684 if (deviceId >= 0) {
685 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
686 if (deviceIndex >= 0) {
687 InputDevice* device = mDevices.valueAt(deviceIndex);
688 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
689 result = (device->*getStateFunc)(sourceMask, code);
690 }
691 }
692 } else {
693 size_t numDevices = mDevices.size();
694 for (size_t i = 0; i < numDevices; i++) {
695 InputDevice* device = mDevices.valueAt(i);
696 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
697 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
698 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
699 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
700 if (currentResult >= AKEY_STATE_DOWN) {
701 return currentResult;
702 } else if (currentResult == AKEY_STATE_UP) {
703 result = currentResult;
704 }
705 }
706 }
707 }
708 return result;
709}
710
Andrii Kulian763a3a42016-03-08 10:46:16 -0800711void InputReader::toggleCapsLockState(int32_t deviceId) {
712 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
713 if (deviceIndex < 0) {
714 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
715 return;
716 }
717
718 InputDevice* device = mDevices.valueAt(deviceIndex);
719 if (device->isIgnored()) {
720 return;
721 }
722
723 device->updateMetaState(AKEYCODE_CAPS_LOCK);
724}
725
Michael Wrightd02c5b62014-02-10 15:10:22 -0800726bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask,
727 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
728 AutoMutex _l(mLock);
729
730 memset(outFlags, 0, numCodes);
731 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
732}
733
734bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
735 size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) {
736 bool result = false;
737 if (deviceId >= 0) {
738 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
739 if (deviceIndex >= 0) {
740 InputDevice* device = mDevices.valueAt(deviceIndex);
741 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
742 result = device->markSupportedKeyCodes(sourceMask,
743 numCodes, keyCodes, outFlags);
744 }
745 }
746 } else {
747 size_t numDevices = mDevices.size();
748 for (size_t i = 0; i < numDevices; i++) {
749 InputDevice* device = mDevices.valueAt(i);
750 if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
751 result |= device->markSupportedKeyCodes(sourceMask,
752 numCodes, keyCodes, outFlags);
753 }
754 }
755 }
756 return result;
757}
758
759void InputReader::requestRefreshConfiguration(uint32_t changes) {
760 AutoMutex _l(mLock);
761
762 if (changes) {
763 bool needWake = !mConfigurationChangesToRefresh;
764 mConfigurationChangesToRefresh |= changes;
765
766 if (needWake) {
767 mEventHub->wake();
768 }
769 }
770}
771
772void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize,
773 ssize_t repeat, int32_t token) {
774 AutoMutex _l(mLock);
775
776 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
777 if (deviceIndex >= 0) {
778 InputDevice* device = mDevices.valueAt(deviceIndex);
779 device->vibrate(pattern, patternSize, repeat, token);
780 }
781}
782
783void InputReader::cancelVibrate(int32_t deviceId, int32_t token) {
784 AutoMutex _l(mLock);
785
786 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
787 if (deviceIndex >= 0) {
788 InputDevice* device = mDevices.valueAt(deviceIndex);
789 device->cancelVibrate(token);
790 }
791}
792
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700793bool InputReader::isInputDeviceEnabled(int32_t deviceId) {
794 AutoMutex _l(mLock);
795
796 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
797 if (deviceIndex >= 0) {
798 InputDevice* device = mDevices.valueAt(deviceIndex);
799 return device->isEnabled();
800 }
801 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
802 return false;
803}
804
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800805void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800806 AutoMutex _l(mLock);
807
808 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800809 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800810
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800811 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800812
813 for (size_t i = 0; i < mDevices.size(); i++) {
814 mDevices.valueAt(i)->dump(dump);
815 }
816
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800817 dump += INDENT "Configuration:\n";
818 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800819 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
820 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800821 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800822 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100823 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800824 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800825 dump += "]\n";
826 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800827 mConfig.virtualKeyQuietTime * 0.000001f);
828
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800829 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800830 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
831 mConfig.pointerVelocityControlParameters.scale,
832 mConfig.pointerVelocityControlParameters.lowThreshold,
833 mConfig.pointerVelocityControlParameters.highThreshold,
834 mConfig.pointerVelocityControlParameters.acceleration);
835
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800836 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Michael Wrightd02c5b62014-02-10 15:10:22 -0800837 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n",
838 mConfig.wheelVelocityControlParameters.scale,
839 mConfig.wheelVelocityControlParameters.lowThreshold,
840 mConfig.wheelVelocityControlParameters.highThreshold,
841 mConfig.wheelVelocityControlParameters.acceleration);
842
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800843 dump += StringPrintf(INDENT2 "PointerGesture:\n");
844 dump += StringPrintf(INDENT3 "Enabled: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800845 toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800847 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800848 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800849 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800852 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 mConfig.pointerGestureTapDragInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800854 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800855 mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800856 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800859 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800860 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800861 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800862 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800863 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800864 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865 mConfig.pointerGestureMovementSpeedRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800866 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -0800867 mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700868
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800869 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700870 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800871}
872
873void InputReader::monitor() {
874 // Acquire and release the lock to ensure that the reader has not deadlocked.
875 mLock.lock();
876 mEventHub->wake();
877 mReaderIsAliveCondition.wait(mLock);
878 mLock.unlock();
879
880 // Check the EventHub
881 mEventHub->monitor();
882}
883
884
885// --- InputReader::ContextImpl ---
886
887InputReader::ContextImpl::ContextImpl(InputReader* reader) :
888 mReader(reader) {
889}
890
891void InputReader::ContextImpl::updateGlobalMetaState() {
892 // lock is already held by the input loop
893 mReader->updateGlobalMetaStateLocked();
894}
895
896int32_t InputReader::ContextImpl::getGlobalMetaState() {
897 // lock is already held by the input loop
898 return mReader->getGlobalMetaStateLocked();
899}
900
901void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
902 // lock is already held by the input loop
903 mReader->disableVirtualKeysUntilLocked(time);
904}
905
906bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now,
907 InputDevice* device, int32_t keyCode, int32_t scanCode) {
908 // lock is already held by the input loop
909 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
910}
911
912void InputReader::ContextImpl::fadePointer() {
913 // lock is already held by the input loop
914 mReader->fadePointerLocked();
915}
916
917void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
918 // lock is already held by the input loop
919 mReader->requestTimeoutAtTimeLocked(when);
920}
921
922int32_t InputReader::ContextImpl::bumpGeneration() {
923 // lock is already held by the input loop
924 return mReader->bumpGenerationLocked();
925}
926
Michael Wright842500e2015-03-13 17:32:02 -0700927void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) {
928 // lock is already held by whatever called refreshConfigurationLocked
929 mReader->getExternalStylusDevicesLocked(outDevices);
930}
931
932void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
933 mReader->dispatchExternalStylusState(state);
934}
935
Michael Wrightd02c5b62014-02-10 15:10:22 -0800936InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
937 return mReader->mPolicy.get();
938}
939
940InputListenerInterface* InputReader::ContextImpl::getListener() {
941 return mReader->mQueuedListener.get();
942}
943
944EventHubInterface* InputReader::ContextImpl::getEventHub() {
945 return mReader->mEventHub.get();
946}
947
948
Michael Wrightd02c5b62014-02-10 15:10:22 -0800949// --- InputDevice ---
950
951InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
952 int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) :
953 mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber),
954 mIdentifier(identifier), mClasses(classes),
Tim Kilbourn063ff532015-04-08 10:26:18 -0700955 mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800956}
957
958InputDevice::~InputDevice() {
959 size_t numMappers = mMappers.size();
960 for (size_t i = 0; i < numMappers; i++) {
961 delete mMappers[i];
962 }
963 mMappers.clear();
964}
965
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -0700966bool InputDevice::isEnabled() {
967 return getEventHub()->isDeviceEnabled(mId);
968}
969
970void InputDevice::setEnabled(bool enabled, nsecs_t when) {
971 if (isEnabled() == enabled) {
972 return;
973 }
974
975 if (enabled) {
976 getEventHub()->enableDevice(mId);
977 reset(when);
978 } else {
979 reset(when);
980 getEventHub()->disableDevice(mId);
981 }
982 // Must change generation to flag this device as changed
983 bumpGeneration();
984}
985
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800986void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800987 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -0700988 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800989
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800990 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100991 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800992 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
993 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -0700994 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
995 if (mAssociatedDisplayPort) {
996 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
997 } else {
998 dump += "<none>\n";
999 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001000 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1001 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1002 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001003
1004 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1005 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001006 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001007 for (size_t i = 0; i < ranges.size(); i++) {
1008 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1009 const char* label = getAxisLabel(range.axis);
1010 char name[32];
1011 if (label) {
1012 strncpy(name, label, sizeof(name));
1013 name[sizeof(name) - 1] = '\0';
1014 } else {
1015 snprintf(name, sizeof(name), "%d", range.axis);
1016 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001017 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001018 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1019 name, range.source, range.min, range.max, range.flat, range.fuzz,
1020 range.resolution);
1021 }
1022 }
1023
1024 size_t numMappers = mMappers.size();
1025 for (size_t i = 0; i < numMappers; i++) {
1026 InputMapper* mapper = mMappers[i];
1027 mapper->dump(dump);
1028 }
1029}
1030
1031void InputDevice::addMapper(InputMapper* mapper) {
1032 mMappers.add(mapper);
1033}
1034
1035void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1036 mSources = 0;
1037
1038 if (!isIgnored()) {
1039 if (!changes) { // first time only
1040 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1041 }
1042
1043 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1044 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1045 sp<KeyCharacterMap> keyboardLayout =
1046 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1047 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1048 bumpGeneration();
1049 }
1050 }
1051 }
1052
1053 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1054 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001055 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001056 if (mAlias != alias) {
1057 mAlias = alias;
1058 bumpGeneration();
1059 }
1060 }
1061 }
1062
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001063 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1064 ssize_t index = config->disabledDevices.indexOf(mId);
1065 bool enabled = index < 0;
1066 setEnabled(enabled, when);
1067 }
1068
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001069 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
1070 // In most situations, no port will be specified.
1071 mAssociatedDisplayPort = std::nullopt;
1072 // Find the display port that corresponds to the current input port.
1073 const std::string& inputPort = mIdentifier.location;
1074 if (!inputPort.empty()) {
1075 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1076 const auto& displayPort = ports.find(inputPort);
1077 if (displayPort != ports.end()) {
1078 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1079 }
1080 }
1081 }
1082
Michael Wrightd02c5b62014-02-10 15:10:22 -08001083 size_t numMappers = mMappers.size();
1084 for (size_t i = 0; i < numMappers; i++) {
1085 InputMapper* mapper = mMappers[i];
1086 mapper->configure(when, config, changes);
1087 mSources |= mapper->getSources();
1088 }
1089 }
1090}
1091
1092void InputDevice::reset(nsecs_t when) {
1093 size_t numMappers = mMappers.size();
1094 for (size_t i = 0; i < numMappers; i++) {
1095 InputMapper* mapper = mMappers[i];
1096 mapper->reset(when);
1097 }
1098
1099 mContext->updateGlobalMetaState();
1100
1101 notifyReset(when);
1102}
1103
1104void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1105 // Process all of the events in order for each mapper.
1106 // We cannot simply ask each mapper to process them in bulk because mappers may
1107 // have side-effects that must be interleaved. For example, joystick movement events and
1108 // gamepad button presses are handled by different mappers but they should be dispatched
1109 // in the order received.
1110 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001111 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001112#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001113 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001114 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1115 rawEvent->when);
1116#endif
1117
1118 if (mDropUntilNextSync) {
1119 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1120 mDropUntilNextSync = false;
1121#if DEBUG_RAW_EVENTS
1122 ALOGD("Recovered from input event buffer overrun.");
1123#endif
1124 } else {
1125#if DEBUG_RAW_EVENTS
1126 ALOGD("Dropped input event while waiting for next input sync.");
1127#endif
1128 }
1129 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001130 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001131 mDropUntilNextSync = true;
1132 reset(rawEvent->when);
1133 } else {
1134 for (size_t i = 0; i < numMappers; i++) {
1135 InputMapper* mapper = mMappers[i];
1136 mapper->process(rawEvent);
1137 }
1138 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001139 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001140 }
1141}
1142
1143void InputDevice::timeoutExpired(nsecs_t when) {
1144 size_t numMappers = mMappers.size();
1145 for (size_t i = 0; i < numMappers; i++) {
1146 InputMapper* mapper = mMappers[i];
1147 mapper->timeoutExpired(when);
1148 }
1149}
1150
Michael Wright842500e2015-03-13 17:32:02 -07001151void InputDevice::updateExternalStylusState(const StylusState& state) {
1152 size_t numMappers = mMappers.size();
1153 for (size_t i = 0; i < numMappers; i++) {
1154 InputMapper* mapper = mMappers[i];
1155 mapper->updateExternalStylusState(state);
1156 }
1157}
1158
Michael Wrightd02c5b62014-02-10 15:10:22 -08001159void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1160 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001161 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001162 size_t numMappers = mMappers.size();
1163 for (size_t i = 0; i < numMappers; i++) {
1164 InputMapper* mapper = mMappers[i];
1165 mapper->populateDeviceInfo(outDeviceInfo);
1166 }
1167}
1168
1169int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1170 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1171}
1172
1173int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1174 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1175}
1176
1177int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1178 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1179}
1180
1181int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1182 int32_t result = AKEY_STATE_UNKNOWN;
1183 size_t numMappers = mMappers.size();
1184 for (size_t i = 0; i < numMappers; i++) {
1185 InputMapper* mapper = mMappers[i];
1186 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1187 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1188 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1189 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1190 if (currentResult >= AKEY_STATE_DOWN) {
1191 return currentResult;
1192 } else if (currentResult == AKEY_STATE_UP) {
1193 result = currentResult;
1194 }
1195 }
1196 }
1197 return result;
1198}
1199
1200bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1201 const int32_t* keyCodes, uint8_t* outFlags) {
1202 bool result = false;
1203 size_t numMappers = mMappers.size();
1204 for (size_t i = 0; i < numMappers; i++) {
1205 InputMapper* mapper = mMappers[i];
1206 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1207 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1208 }
1209 }
1210 return result;
1211}
1212
1213void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1214 int32_t token) {
1215 size_t numMappers = mMappers.size();
1216 for (size_t i = 0; i < numMappers; i++) {
1217 InputMapper* mapper = mMappers[i];
1218 mapper->vibrate(pattern, patternSize, repeat, token);
1219 }
1220}
1221
1222void InputDevice::cancelVibrate(int32_t token) {
1223 size_t numMappers = mMappers.size();
1224 for (size_t i = 0; i < numMappers; i++) {
1225 InputMapper* mapper = mMappers[i];
1226 mapper->cancelVibrate(token);
1227 }
1228}
1229
Jeff Brownc9aa6282015-02-11 19:03:28 -08001230void InputDevice::cancelTouch(nsecs_t when) {
1231 size_t numMappers = mMappers.size();
1232 for (size_t i = 0; i < numMappers; i++) {
1233 InputMapper* mapper = mMappers[i];
1234 mapper->cancelTouch(when);
1235 }
1236}
1237
Michael Wrightd02c5b62014-02-10 15:10:22 -08001238int32_t InputDevice::getMetaState() {
1239 int32_t result = 0;
1240 size_t numMappers = mMappers.size();
1241 for (size_t i = 0; i < numMappers; i++) {
1242 InputMapper* mapper = mMappers[i];
1243 result |= mapper->getMetaState();
1244 }
1245 return result;
1246}
1247
Andrii Kulian763a3a42016-03-08 10:46:16 -08001248void InputDevice::updateMetaState(int32_t keyCode) {
1249 size_t numMappers = mMappers.size();
1250 for (size_t i = 0; i < numMappers; i++) {
1251 mMappers[i]->updateMetaState(keyCode);
1252 }
1253}
1254
Michael Wrightd02c5b62014-02-10 15:10:22 -08001255void InputDevice::fadePointer() {
1256 size_t numMappers = mMappers.size();
1257 for (size_t i = 0; i < numMappers; i++) {
1258 InputMapper* mapper = mMappers[i];
1259 mapper->fadePointer();
1260 }
1261}
1262
1263void InputDevice::bumpGeneration() {
1264 mGeneration = mContext->bumpGeneration();
1265}
1266
1267void InputDevice::notifyReset(nsecs_t when) {
1268 NotifyDeviceResetArgs args(when, mId);
1269 mContext->getListener()->notifyDeviceReset(&args);
1270}
1271
1272
1273// --- CursorButtonAccumulator ---
1274
1275CursorButtonAccumulator::CursorButtonAccumulator() {
1276 clearButtons();
1277}
1278
1279void CursorButtonAccumulator::reset(InputDevice* device) {
1280 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1281 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1282 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1283 mBtnBack = device->isKeyPressed(BTN_BACK);
1284 mBtnSide = device->isKeyPressed(BTN_SIDE);
1285 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1286 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1287 mBtnTask = device->isKeyPressed(BTN_TASK);
1288}
1289
1290void CursorButtonAccumulator::clearButtons() {
1291 mBtnLeft = 0;
1292 mBtnRight = 0;
1293 mBtnMiddle = 0;
1294 mBtnBack = 0;
1295 mBtnSide = 0;
1296 mBtnForward = 0;
1297 mBtnExtra = 0;
1298 mBtnTask = 0;
1299}
1300
1301void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1302 if (rawEvent->type == EV_KEY) {
1303 switch (rawEvent->code) {
1304 case BTN_LEFT:
1305 mBtnLeft = rawEvent->value;
1306 break;
1307 case BTN_RIGHT:
1308 mBtnRight = rawEvent->value;
1309 break;
1310 case BTN_MIDDLE:
1311 mBtnMiddle = rawEvent->value;
1312 break;
1313 case BTN_BACK:
1314 mBtnBack = rawEvent->value;
1315 break;
1316 case BTN_SIDE:
1317 mBtnSide = rawEvent->value;
1318 break;
1319 case BTN_FORWARD:
1320 mBtnForward = rawEvent->value;
1321 break;
1322 case BTN_EXTRA:
1323 mBtnExtra = rawEvent->value;
1324 break;
1325 case BTN_TASK:
1326 mBtnTask = rawEvent->value;
1327 break;
1328 }
1329 }
1330}
1331
1332uint32_t CursorButtonAccumulator::getButtonState() const {
1333 uint32_t result = 0;
1334 if (mBtnLeft) {
1335 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1336 }
1337 if (mBtnRight) {
1338 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1339 }
1340 if (mBtnMiddle) {
1341 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1342 }
1343 if (mBtnBack || mBtnSide) {
1344 result |= AMOTION_EVENT_BUTTON_BACK;
1345 }
1346 if (mBtnForward || mBtnExtra) {
1347 result |= AMOTION_EVENT_BUTTON_FORWARD;
1348 }
1349 return result;
1350}
1351
1352
1353// --- CursorMotionAccumulator ---
1354
1355CursorMotionAccumulator::CursorMotionAccumulator() {
1356 clearRelativeAxes();
1357}
1358
1359void CursorMotionAccumulator::reset(InputDevice* device) {
1360 clearRelativeAxes();
1361}
1362
1363void CursorMotionAccumulator::clearRelativeAxes() {
1364 mRelX = 0;
1365 mRelY = 0;
1366}
1367
1368void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1369 if (rawEvent->type == EV_REL) {
1370 switch (rawEvent->code) {
1371 case REL_X:
1372 mRelX = rawEvent->value;
1373 break;
1374 case REL_Y:
1375 mRelY = rawEvent->value;
1376 break;
1377 }
1378 }
1379}
1380
1381void CursorMotionAccumulator::finishSync() {
1382 clearRelativeAxes();
1383}
1384
1385
1386// --- CursorScrollAccumulator ---
1387
1388CursorScrollAccumulator::CursorScrollAccumulator() :
1389 mHaveRelWheel(false), mHaveRelHWheel(false) {
1390 clearRelativeAxes();
1391}
1392
1393void CursorScrollAccumulator::configure(InputDevice* device) {
1394 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1395 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1396}
1397
1398void CursorScrollAccumulator::reset(InputDevice* device) {
1399 clearRelativeAxes();
1400}
1401
1402void CursorScrollAccumulator::clearRelativeAxes() {
1403 mRelWheel = 0;
1404 mRelHWheel = 0;
1405}
1406
1407void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1408 if (rawEvent->type == EV_REL) {
1409 switch (rawEvent->code) {
1410 case REL_WHEEL:
1411 mRelWheel = rawEvent->value;
1412 break;
1413 case REL_HWHEEL:
1414 mRelHWheel = rawEvent->value;
1415 break;
1416 }
1417 }
1418}
1419
1420void CursorScrollAccumulator::finishSync() {
1421 clearRelativeAxes();
1422}
1423
1424
1425// --- TouchButtonAccumulator ---
1426
1427TouchButtonAccumulator::TouchButtonAccumulator() :
1428 mHaveBtnTouch(false), mHaveStylus(false) {
1429 clearButtons();
1430}
1431
1432void TouchButtonAccumulator::configure(InputDevice* device) {
1433 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1434 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1435 || device->hasKey(BTN_TOOL_RUBBER)
1436 || device->hasKey(BTN_TOOL_BRUSH)
1437 || device->hasKey(BTN_TOOL_PENCIL)
1438 || device->hasKey(BTN_TOOL_AIRBRUSH);
1439}
1440
1441void TouchButtonAccumulator::reset(InputDevice* device) {
1442 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1443 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001444 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1445 mBtnStylus2 =
1446 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001447 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1448 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1449 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1450 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1451 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1452 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1453 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1454 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1455 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1456 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1457 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1458}
1459
1460void TouchButtonAccumulator::clearButtons() {
1461 mBtnTouch = 0;
1462 mBtnStylus = 0;
1463 mBtnStylus2 = 0;
1464 mBtnToolFinger = 0;
1465 mBtnToolPen = 0;
1466 mBtnToolRubber = 0;
1467 mBtnToolBrush = 0;
1468 mBtnToolPencil = 0;
1469 mBtnToolAirbrush = 0;
1470 mBtnToolMouse = 0;
1471 mBtnToolLens = 0;
1472 mBtnToolDoubleTap = 0;
1473 mBtnToolTripleTap = 0;
1474 mBtnToolQuadTap = 0;
1475}
1476
1477void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1478 if (rawEvent->type == EV_KEY) {
1479 switch (rawEvent->code) {
1480 case BTN_TOUCH:
1481 mBtnTouch = rawEvent->value;
1482 break;
1483 case BTN_STYLUS:
1484 mBtnStylus = rawEvent->value;
1485 break;
1486 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001487 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001488 mBtnStylus2 = rawEvent->value;
1489 break;
1490 case BTN_TOOL_FINGER:
1491 mBtnToolFinger = rawEvent->value;
1492 break;
1493 case BTN_TOOL_PEN:
1494 mBtnToolPen = rawEvent->value;
1495 break;
1496 case BTN_TOOL_RUBBER:
1497 mBtnToolRubber = rawEvent->value;
1498 break;
1499 case BTN_TOOL_BRUSH:
1500 mBtnToolBrush = rawEvent->value;
1501 break;
1502 case BTN_TOOL_PENCIL:
1503 mBtnToolPencil = rawEvent->value;
1504 break;
1505 case BTN_TOOL_AIRBRUSH:
1506 mBtnToolAirbrush = rawEvent->value;
1507 break;
1508 case BTN_TOOL_MOUSE:
1509 mBtnToolMouse = rawEvent->value;
1510 break;
1511 case BTN_TOOL_LENS:
1512 mBtnToolLens = rawEvent->value;
1513 break;
1514 case BTN_TOOL_DOUBLETAP:
1515 mBtnToolDoubleTap = rawEvent->value;
1516 break;
1517 case BTN_TOOL_TRIPLETAP:
1518 mBtnToolTripleTap = rawEvent->value;
1519 break;
1520 case BTN_TOOL_QUADTAP:
1521 mBtnToolQuadTap = rawEvent->value;
1522 break;
1523 }
1524 }
1525}
1526
1527uint32_t TouchButtonAccumulator::getButtonState() const {
1528 uint32_t result = 0;
1529 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001530 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001531 }
1532 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001533 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001534 }
1535 return result;
1536}
1537
1538int32_t TouchButtonAccumulator::getToolType() const {
1539 if (mBtnToolMouse || mBtnToolLens) {
1540 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1541 }
1542 if (mBtnToolRubber) {
1543 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1544 }
1545 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1546 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1547 }
1548 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1549 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1550 }
1551 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1552}
1553
1554bool TouchButtonAccumulator::isToolActive() const {
1555 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1556 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1557 || mBtnToolMouse || mBtnToolLens
1558 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1559}
1560
1561bool TouchButtonAccumulator::isHovering() const {
1562 return mHaveBtnTouch && !mBtnTouch;
1563}
1564
1565bool TouchButtonAccumulator::hasStylus() const {
1566 return mHaveStylus;
1567}
1568
1569
1570// --- RawPointerAxes ---
1571
1572RawPointerAxes::RawPointerAxes() {
1573 clear();
1574}
1575
1576void RawPointerAxes::clear() {
1577 x.clear();
1578 y.clear();
1579 pressure.clear();
1580 touchMajor.clear();
1581 touchMinor.clear();
1582 toolMajor.clear();
1583 toolMinor.clear();
1584 orientation.clear();
1585 distance.clear();
1586 tiltX.clear();
1587 tiltY.clear();
1588 trackingId.clear();
1589 slot.clear();
1590}
1591
1592
1593// --- RawPointerData ---
1594
1595RawPointerData::RawPointerData() {
1596 clear();
1597}
1598
1599void RawPointerData::clear() {
1600 pointerCount = 0;
1601 clearIdBits();
1602}
1603
1604void RawPointerData::copyFrom(const RawPointerData& other) {
1605 pointerCount = other.pointerCount;
1606 hoveringIdBits = other.hoveringIdBits;
1607 touchingIdBits = other.touchingIdBits;
1608
1609 for (uint32_t i = 0; i < pointerCount; i++) {
1610 pointers[i] = other.pointers[i];
1611
1612 int id = pointers[i].id;
1613 idToIndex[id] = other.idToIndex[id];
1614 }
1615}
1616
1617void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1618 float x = 0, y = 0;
1619 uint32_t count = touchingIdBits.count();
1620 if (count) {
1621 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1622 uint32_t id = idBits.clearFirstMarkedBit();
1623 const Pointer& pointer = pointerForId(id);
1624 x += pointer.x;
1625 y += pointer.y;
1626 }
1627 x /= count;
1628 y /= count;
1629 }
1630 *outX = x;
1631 *outY = y;
1632}
1633
1634
1635// --- CookedPointerData ---
1636
1637CookedPointerData::CookedPointerData() {
1638 clear();
1639}
1640
1641void CookedPointerData::clear() {
1642 pointerCount = 0;
1643 hoveringIdBits.clear();
1644 touchingIdBits.clear();
1645}
1646
1647void CookedPointerData::copyFrom(const CookedPointerData& other) {
1648 pointerCount = other.pointerCount;
1649 hoveringIdBits = other.hoveringIdBits;
1650 touchingIdBits = other.touchingIdBits;
1651
1652 for (uint32_t i = 0; i < pointerCount; i++) {
1653 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1654 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1655
1656 int id = pointerProperties[i].id;
1657 idToIndex[id] = other.idToIndex[id];
1658 }
1659}
1660
1661
1662// --- SingleTouchMotionAccumulator ---
1663
1664SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1665 clearAbsoluteAxes();
1666}
1667
1668void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1669 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1670 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1671 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1672 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1673 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1674 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1675 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1676}
1677
1678void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1679 mAbsX = 0;
1680 mAbsY = 0;
1681 mAbsPressure = 0;
1682 mAbsToolWidth = 0;
1683 mAbsDistance = 0;
1684 mAbsTiltX = 0;
1685 mAbsTiltY = 0;
1686}
1687
1688void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1689 if (rawEvent->type == EV_ABS) {
1690 switch (rawEvent->code) {
1691 case ABS_X:
1692 mAbsX = rawEvent->value;
1693 break;
1694 case ABS_Y:
1695 mAbsY = rawEvent->value;
1696 break;
1697 case ABS_PRESSURE:
1698 mAbsPressure = rawEvent->value;
1699 break;
1700 case ABS_TOOL_WIDTH:
1701 mAbsToolWidth = rawEvent->value;
1702 break;
1703 case ABS_DISTANCE:
1704 mAbsDistance = rawEvent->value;
1705 break;
1706 case ABS_TILT_X:
1707 mAbsTiltX = rawEvent->value;
1708 break;
1709 case ABS_TILT_Y:
1710 mAbsTiltY = rawEvent->value;
1711 break;
1712 }
1713 }
1714}
1715
1716
1717// --- MultiTouchMotionAccumulator ---
1718
1719MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001720 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001721 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001722}
1723
1724MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1725 delete[] mSlots;
1726}
1727
1728void MultiTouchMotionAccumulator::configure(InputDevice* device,
1729 size_t slotCount, bool usingSlotsProtocol) {
1730 mSlotCount = slotCount;
1731 mUsingSlotsProtocol = usingSlotsProtocol;
1732 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1733
1734 delete[] mSlots;
1735 mSlots = new Slot[slotCount];
1736}
1737
1738void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1739 // Unfortunately there is no way to read the initial contents of the slots.
1740 // So when we reset the accumulator, we must assume they are all zeroes.
1741 if (mUsingSlotsProtocol) {
1742 // Query the driver for the current slot index and use it as the initial slot
1743 // before we start reading events from the device. It is possible that the
1744 // current slot index will not be the same as it was when the first event was
1745 // written into the evdev buffer, which means the input mapper could start
1746 // out of sync with the initial state of the events in the evdev buffer.
1747 // In the extremely unlikely case that this happens, the data from
1748 // two slots will be confused until the next ABS_MT_SLOT event is received.
1749 // This can cause the touch point to "jump", but at least there will be
1750 // no stuck touches.
1751 int32_t initialSlot;
1752 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1753 ABS_MT_SLOT, &initialSlot);
1754 if (status) {
1755 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1756 initialSlot = -1;
1757 }
1758 clearSlots(initialSlot);
1759 } else {
1760 clearSlots(-1);
1761 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001762 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001763}
1764
1765void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1766 if (mSlots) {
1767 for (size_t i = 0; i < mSlotCount; i++) {
1768 mSlots[i].clear();
1769 }
1770 }
1771 mCurrentSlot = initialSlot;
1772}
1773
1774void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1775 if (rawEvent->type == EV_ABS) {
1776 bool newSlot = false;
1777 if (mUsingSlotsProtocol) {
1778 if (rawEvent->code == ABS_MT_SLOT) {
1779 mCurrentSlot = rawEvent->value;
1780 newSlot = true;
1781 }
1782 } else if (mCurrentSlot < 0) {
1783 mCurrentSlot = 0;
1784 }
1785
1786 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1787#if DEBUG_POINTERS
1788 if (newSlot) {
1789 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001790 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001791 mCurrentSlot, mSlotCount - 1);
1792 }
1793#endif
1794 } else {
1795 Slot* slot = &mSlots[mCurrentSlot];
1796
1797 switch (rawEvent->code) {
1798 case ABS_MT_POSITION_X:
1799 slot->mInUse = true;
1800 slot->mAbsMTPositionX = rawEvent->value;
1801 break;
1802 case ABS_MT_POSITION_Y:
1803 slot->mInUse = true;
1804 slot->mAbsMTPositionY = rawEvent->value;
1805 break;
1806 case ABS_MT_TOUCH_MAJOR:
1807 slot->mInUse = true;
1808 slot->mAbsMTTouchMajor = rawEvent->value;
1809 break;
1810 case ABS_MT_TOUCH_MINOR:
1811 slot->mInUse = true;
1812 slot->mAbsMTTouchMinor = rawEvent->value;
1813 slot->mHaveAbsMTTouchMinor = true;
1814 break;
1815 case ABS_MT_WIDTH_MAJOR:
1816 slot->mInUse = true;
1817 slot->mAbsMTWidthMajor = rawEvent->value;
1818 break;
1819 case ABS_MT_WIDTH_MINOR:
1820 slot->mInUse = true;
1821 slot->mAbsMTWidthMinor = rawEvent->value;
1822 slot->mHaveAbsMTWidthMinor = true;
1823 break;
1824 case ABS_MT_ORIENTATION:
1825 slot->mInUse = true;
1826 slot->mAbsMTOrientation = rawEvent->value;
1827 break;
1828 case ABS_MT_TRACKING_ID:
1829 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1830 // The slot is no longer in use but it retains its previous contents,
1831 // which may be reused for subsequent touches.
1832 slot->mInUse = false;
1833 } else {
1834 slot->mInUse = true;
1835 slot->mAbsMTTrackingId = rawEvent->value;
1836 }
1837 break;
1838 case ABS_MT_PRESSURE:
1839 slot->mInUse = true;
1840 slot->mAbsMTPressure = rawEvent->value;
1841 break;
1842 case ABS_MT_DISTANCE:
1843 slot->mInUse = true;
1844 slot->mAbsMTDistance = rawEvent->value;
1845 break;
1846 case ABS_MT_TOOL_TYPE:
1847 slot->mInUse = true;
1848 slot->mAbsMTToolType = rawEvent->value;
1849 slot->mHaveAbsMTToolType = true;
1850 break;
1851 }
1852 }
1853 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1854 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1855 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001856 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1857 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001858 }
1859}
1860
1861void MultiTouchMotionAccumulator::finishSync() {
1862 if (!mUsingSlotsProtocol) {
1863 clearSlots(-1);
1864 }
1865}
1866
1867bool MultiTouchMotionAccumulator::hasStylus() const {
1868 return mHaveStylus;
1869}
1870
1871
1872// --- MultiTouchMotionAccumulator::Slot ---
1873
1874MultiTouchMotionAccumulator::Slot::Slot() {
1875 clear();
1876}
1877
1878void MultiTouchMotionAccumulator::Slot::clear() {
1879 mInUse = false;
1880 mHaveAbsMTTouchMinor = false;
1881 mHaveAbsMTWidthMinor = false;
1882 mHaveAbsMTToolType = false;
1883 mAbsMTPositionX = 0;
1884 mAbsMTPositionY = 0;
1885 mAbsMTTouchMajor = 0;
1886 mAbsMTTouchMinor = 0;
1887 mAbsMTWidthMajor = 0;
1888 mAbsMTWidthMinor = 0;
1889 mAbsMTOrientation = 0;
1890 mAbsMTTrackingId = -1;
1891 mAbsMTPressure = 0;
1892 mAbsMTDistance = 0;
1893 mAbsMTToolType = 0;
1894}
1895
1896int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1897 if (mHaveAbsMTToolType) {
1898 switch (mAbsMTToolType) {
1899 case MT_TOOL_FINGER:
1900 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1901 case MT_TOOL_PEN:
1902 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1903 }
1904 }
1905 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1906}
1907
1908
1909// --- InputMapper ---
1910
1911InputMapper::InputMapper(InputDevice* device) :
1912 mDevice(device), mContext(device->getContext()) {
1913}
1914
1915InputMapper::~InputMapper() {
1916}
1917
1918void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1919 info->addSource(getSources());
1920}
1921
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001922void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001923}
1924
1925void InputMapper::configure(nsecs_t when,
1926 const InputReaderConfiguration* config, uint32_t changes) {
1927}
1928
1929void InputMapper::reset(nsecs_t when) {
1930}
1931
1932void InputMapper::timeoutExpired(nsecs_t when) {
1933}
1934
1935int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1936 return AKEY_STATE_UNKNOWN;
1937}
1938
1939int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1940 return AKEY_STATE_UNKNOWN;
1941}
1942
1943int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1944 return AKEY_STATE_UNKNOWN;
1945}
1946
1947bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1948 const int32_t* keyCodes, uint8_t* outFlags) {
1949 return false;
1950}
1951
1952void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1953 int32_t token) {
1954}
1955
1956void InputMapper::cancelVibrate(int32_t token) {
1957}
1958
Jeff Brownc9aa6282015-02-11 19:03:28 -08001959void InputMapper::cancelTouch(nsecs_t when) {
1960}
1961
Michael Wrightd02c5b62014-02-10 15:10:22 -08001962int32_t InputMapper::getMetaState() {
1963 return 0;
1964}
1965
Andrii Kulian763a3a42016-03-08 10:46:16 -08001966void InputMapper::updateMetaState(int32_t keyCode) {
1967}
1968
Michael Wright842500e2015-03-13 17:32:02 -07001969void InputMapper::updateExternalStylusState(const StylusState& state) {
1970
1971}
1972
Michael Wrightd02c5b62014-02-10 15:10:22 -08001973void InputMapper::fadePointer() {
1974}
1975
1976status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1977 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1978}
1979
1980void InputMapper::bumpGeneration() {
1981 mDevice->bumpGeneration();
1982}
1983
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001984void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985 const RawAbsoluteAxisInfo& axis, const char* name) {
1986 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001987 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001988 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1989 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001990 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001991 }
1992}
1993
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001994void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1995 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1996 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
1997 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
1998 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07001999}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002000
2001// --- SwitchInputMapper ---
2002
2003SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002004 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002005}
2006
2007SwitchInputMapper::~SwitchInputMapper() {
2008}
2009
2010uint32_t SwitchInputMapper::getSources() {
2011 return AINPUT_SOURCE_SWITCH;
2012}
2013
2014void SwitchInputMapper::process(const RawEvent* rawEvent) {
2015 switch (rawEvent->type) {
2016 case EV_SW:
2017 processSwitch(rawEvent->code, rawEvent->value);
2018 break;
2019
2020 case EV_SYN:
2021 if (rawEvent->code == SYN_REPORT) {
2022 sync(rawEvent->when);
2023 }
2024 }
2025}
2026
2027void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2028 if (switchCode >= 0 && switchCode < 32) {
2029 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002030 mSwitchValues |= 1 << switchCode;
2031 } else {
2032 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002033 }
2034 mUpdatedSwitchMask |= 1 << switchCode;
2035 }
2036}
2037
2038void SwitchInputMapper::sync(nsecs_t when) {
2039 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002040 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002041 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002042 getListener()->notifySwitch(&args);
2043
Michael Wrightd02c5b62014-02-10 15:10:22 -08002044 mUpdatedSwitchMask = 0;
2045 }
2046}
2047
2048int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2049 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2050}
2051
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002052void SwitchInputMapper::dump(std::string& dump) {
2053 dump += INDENT2 "Switch Input Mapper:\n";
2054 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002055}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002056
2057// --- VibratorInputMapper ---
2058
2059VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2060 InputMapper(device), mVibrating(false) {
2061}
2062
2063VibratorInputMapper::~VibratorInputMapper() {
2064}
2065
2066uint32_t VibratorInputMapper::getSources() {
2067 return 0;
2068}
2069
2070void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2071 InputMapper::populateDeviceInfo(info);
2072
2073 info->setVibrator(true);
2074}
2075
2076void VibratorInputMapper::process(const RawEvent* rawEvent) {
2077 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2078}
2079
2080void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2081 int32_t token) {
2082#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002083 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002084 for (size_t i = 0; i < patternSize; i++) {
2085 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002086 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002087 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002088 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002089 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002090 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002091 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002092#endif
2093
2094 mVibrating = true;
2095 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2096 mPatternSize = patternSize;
2097 mRepeat = repeat;
2098 mToken = token;
2099 mIndex = -1;
2100
2101 nextStep();
2102}
2103
2104void VibratorInputMapper::cancelVibrate(int32_t token) {
2105#if DEBUG_VIBRATOR
2106 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2107#endif
2108
2109 if (mVibrating && mToken == token) {
2110 stopVibrating();
2111 }
2112}
2113
2114void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2115 if (mVibrating) {
2116 if (when >= mNextStepTime) {
2117 nextStep();
2118 } else {
2119 getContext()->requestTimeoutAtTime(mNextStepTime);
2120 }
2121 }
2122}
2123
2124void VibratorInputMapper::nextStep() {
2125 mIndex += 1;
2126 if (size_t(mIndex) >= mPatternSize) {
2127 if (mRepeat < 0) {
2128 // We are done.
2129 stopVibrating();
2130 return;
2131 }
2132 mIndex = mRepeat;
2133 }
2134
2135 bool vibratorOn = mIndex & 1;
2136 nsecs_t duration = mPattern[mIndex];
2137 if (vibratorOn) {
2138#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002139 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002140#endif
2141 getEventHub()->vibrate(getDeviceId(), duration);
2142 } else {
2143#if DEBUG_VIBRATOR
2144 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2145#endif
2146 getEventHub()->cancelVibrate(getDeviceId());
2147 }
2148 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2149 mNextStepTime = now + duration;
2150 getContext()->requestTimeoutAtTime(mNextStepTime);
2151#if DEBUG_VIBRATOR
2152 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2153#endif
2154}
2155
2156void VibratorInputMapper::stopVibrating() {
2157 mVibrating = false;
2158#if DEBUG_VIBRATOR
2159 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2160#endif
2161 getEventHub()->cancelVibrate(getDeviceId());
2162}
2163
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002164void VibratorInputMapper::dump(std::string& dump) {
2165 dump += INDENT2 "Vibrator Input Mapper:\n";
2166 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002167}
2168
2169
2170// --- KeyboardInputMapper ---
2171
2172KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2173 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002174 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002175}
2176
2177KeyboardInputMapper::~KeyboardInputMapper() {
2178}
2179
2180uint32_t KeyboardInputMapper::getSources() {
2181 return mSource;
2182}
2183
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002184int32_t KeyboardInputMapper::getOrientation() {
2185 if (mViewport) {
2186 return mViewport->orientation;
2187 }
2188 return DISPLAY_ORIENTATION_0;
2189}
2190
2191int32_t KeyboardInputMapper::getDisplayId() {
2192 if (mViewport) {
2193 return mViewport->displayId;
2194 }
2195 return ADISPLAY_ID_NONE;
2196}
2197
Michael Wrightd02c5b62014-02-10 15:10:22 -08002198void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2199 InputMapper::populateDeviceInfo(info);
2200
2201 info->setKeyboardType(mKeyboardType);
2202 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2203}
2204
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002205void KeyboardInputMapper::dump(std::string& dump) {
2206 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002208 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002209 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002210 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2211 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2212 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002213}
2214
Michael Wrightd02c5b62014-02-10 15:10:22 -08002215void KeyboardInputMapper::configure(nsecs_t when,
2216 const InputReaderConfiguration* config, uint32_t changes) {
2217 InputMapper::configure(when, config, changes);
2218
2219 if (!changes) { // first time only
2220 // Configure basic parameters.
2221 configureParameters();
2222 }
2223
2224 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002225 if (mParameters.orientationAware) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002226 mViewport = config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 }
2228 }
2229}
2230
Ivan Podogovb9afef32017-02-13 15:34:32 +00002231static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2232 int32_t mapped = 0;
2233 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2234 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2235 if (stemKeyRotationMap[i][0] == keyCode) {
2236 stemKeyRotationMap[i][1] = mapped;
2237 return;
2238 }
2239 }
2240 }
2241}
2242
Michael Wrightd02c5b62014-02-10 15:10:22 -08002243void KeyboardInputMapper::configureParameters() {
2244 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002245 const PropertyMap& config = getDevice()->getConfiguration();
2246 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247 mParameters.orientationAware);
2248
Michael Wrightd02c5b62014-02-10 15:10:22 -08002249 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002250 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2251 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2252 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2253 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002254 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002255
2256 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002257 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002258 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002259}
2260
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002261void KeyboardInputMapper::dumpParameters(std::string& dump) {
2262 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002263 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002264 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002265 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002266 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002267}
2268
2269void KeyboardInputMapper::reset(nsecs_t when) {
2270 mMetaState = AMETA_NONE;
2271 mDownTime = 0;
2272 mKeyDowns.clear();
2273 mCurrentHidUsage = 0;
2274
2275 resetLedState();
2276
2277 InputMapper::reset(when);
2278}
2279
2280void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2281 switch (rawEvent->type) {
2282 case EV_KEY: {
2283 int32_t scanCode = rawEvent->code;
2284 int32_t usageCode = mCurrentHidUsage;
2285 mCurrentHidUsage = 0;
2286
2287 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002288 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002289 }
2290 break;
2291 }
2292 case EV_MSC: {
2293 if (rawEvent->code == MSC_SCAN) {
2294 mCurrentHidUsage = rawEvent->value;
2295 }
2296 break;
2297 }
2298 case EV_SYN: {
2299 if (rawEvent->code == SYN_REPORT) {
2300 mCurrentHidUsage = 0;
2301 }
2302 }
2303 }
2304}
2305
2306bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2307 return scanCode < BTN_MOUSE
2308 || scanCode >= KEY_OK
2309 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2310 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2311}
2312
Michael Wright58ba9882017-07-26 16:19:11 +01002313bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2314 switch (keyCode) {
2315 case AKEYCODE_MEDIA_PLAY:
2316 case AKEYCODE_MEDIA_PAUSE:
2317 case AKEYCODE_MEDIA_PLAY_PAUSE:
2318 case AKEYCODE_MUTE:
2319 case AKEYCODE_HEADSETHOOK:
2320 case AKEYCODE_MEDIA_STOP:
2321 case AKEYCODE_MEDIA_NEXT:
2322 case AKEYCODE_MEDIA_PREVIOUS:
2323 case AKEYCODE_MEDIA_REWIND:
2324 case AKEYCODE_MEDIA_RECORD:
2325 case AKEYCODE_MEDIA_FAST_FORWARD:
2326 case AKEYCODE_MEDIA_SKIP_FORWARD:
2327 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2328 case AKEYCODE_MEDIA_STEP_FORWARD:
2329 case AKEYCODE_MEDIA_STEP_BACKWARD:
2330 case AKEYCODE_MEDIA_AUDIO_TRACK:
2331 case AKEYCODE_VOLUME_UP:
2332 case AKEYCODE_VOLUME_DOWN:
2333 case AKEYCODE_VOLUME_MUTE:
2334 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2335 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2336 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2337 return true;
2338 }
2339 return false;
2340}
2341
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002342void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2343 int32_t usageCode) {
2344 int32_t keyCode;
2345 int32_t keyMetaState;
2346 uint32_t policyFlags;
2347
2348 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2349 &keyCode, &keyMetaState, &policyFlags)) {
2350 keyCode = AKEYCODE_UNKNOWN;
2351 keyMetaState = mMetaState;
2352 policyFlags = 0;
2353 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002354
2355 if (down) {
2356 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002357 if (mParameters.orientationAware) {
2358 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002359 }
2360
2361 // Add key down.
2362 ssize_t keyDownIndex = findKeyDown(scanCode);
2363 if (keyDownIndex >= 0) {
2364 // key repeat, be sure to use same keycode as before in case of rotation
2365 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2366 } else {
2367 // key down
2368 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2369 && mContext->shouldDropVirtualKey(when,
2370 getDevice(), keyCode, scanCode)) {
2371 return;
2372 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002373 if (policyFlags & POLICY_FLAG_GESTURE) {
2374 mDevice->cancelTouch(when);
2375 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376
2377 mKeyDowns.push();
2378 KeyDown& keyDown = mKeyDowns.editTop();
2379 keyDown.keyCode = keyCode;
2380 keyDown.scanCode = scanCode;
2381 }
2382
2383 mDownTime = when;
2384 } else {
2385 // Remove key down.
2386 ssize_t keyDownIndex = findKeyDown(scanCode);
2387 if (keyDownIndex >= 0) {
2388 // key up, be sure to use same keycode as before in case of rotation
2389 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2390 mKeyDowns.removeAt(size_t(keyDownIndex));
2391 } else {
2392 // key was not actually down
2393 ALOGI("Dropping key up from device %s because the key was not down. "
2394 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002395 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002396 return;
2397 }
2398 }
2399
Andrii Kulian763a3a42016-03-08 10:46:16 -08002400 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002401 // If global meta state changed send it along with the key.
2402 // If it has not changed then we'll use what keymap gave us,
2403 // since key replacement logic might temporarily reset a few
2404 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002405 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 }
2407
2408 nsecs_t downTime = mDownTime;
2409
2410 // Key down on external an keyboard should wake the device.
2411 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2412 // For internal keyboards, the key layout file should specify the policy flags for
2413 // each wake key individually.
2414 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002415 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002416 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002417 }
2418
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002419 if (mParameters.handlesKeyRepeat) {
2420 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2421 }
2422
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002423 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002424 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002425 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002426 getListener()->notifyKey(&args);
2427}
2428
2429ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2430 size_t n = mKeyDowns.size();
2431 for (size_t i = 0; i < n; i++) {
2432 if (mKeyDowns[i].scanCode == scanCode) {
2433 return i;
2434 }
2435 }
2436 return -1;
2437}
2438
2439int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2440 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2441}
2442
2443int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2444 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2445}
2446
2447bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2448 const int32_t* keyCodes, uint8_t* outFlags) {
2449 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2450}
2451
2452int32_t KeyboardInputMapper::getMetaState() {
2453 return mMetaState;
2454}
2455
Andrii Kulian763a3a42016-03-08 10:46:16 -08002456void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2457 updateMetaStateIfNeeded(keyCode, false);
2458}
2459
2460bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2461 int32_t oldMetaState = mMetaState;
2462 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2463 bool metaStateChanged = oldMetaState != newMetaState;
2464 if (metaStateChanged) {
2465 mMetaState = newMetaState;
2466 updateLedState(false);
2467
2468 getContext()->updateGlobalMetaState();
2469 }
2470
2471 return metaStateChanged;
2472}
2473
Michael Wrightd02c5b62014-02-10 15:10:22 -08002474void KeyboardInputMapper::resetLedState() {
2475 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2476 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2477 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2478
2479 updateLedState(true);
2480}
2481
2482void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2483 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2484 ledState.on = false;
2485}
2486
2487void KeyboardInputMapper::updateLedState(bool reset) {
2488 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2489 AMETA_CAPS_LOCK_ON, reset);
2490 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2491 AMETA_NUM_LOCK_ON, reset);
2492 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2493 AMETA_SCROLL_LOCK_ON, reset);
2494}
2495
2496void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2497 int32_t led, int32_t modifier, bool reset) {
2498 if (ledState.avail) {
2499 bool desiredState = (mMetaState & modifier) != 0;
2500 if (reset || ledState.on != desiredState) {
2501 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2502 ledState.on = desiredState;
2503 }
2504 }
2505}
2506
2507
2508// --- CursorInputMapper ---
2509
2510CursorInputMapper::CursorInputMapper(InputDevice* device) :
2511 InputMapper(device) {
2512}
2513
2514CursorInputMapper::~CursorInputMapper() {
2515}
2516
2517uint32_t CursorInputMapper::getSources() {
2518 return mSource;
2519}
2520
2521void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2522 InputMapper::populateDeviceInfo(info);
2523
2524 if (mParameters.mode == Parameters::MODE_POINTER) {
2525 float minX, minY, maxX, maxY;
2526 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2527 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2528 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2529 }
2530 } else {
2531 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2532 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2533 }
2534 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2535
2536 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2537 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2538 }
2539 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2540 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2541 }
2542}
2543
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002544void CursorInputMapper::dump(std::string& dump) {
2545 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002546 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002547 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2548 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2549 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2550 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2551 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002552 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002553 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002554 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002555 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2556 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2557 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2558 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2559 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2560 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002561}
2562
2563void CursorInputMapper::configure(nsecs_t when,
2564 const InputReaderConfiguration* config, uint32_t changes) {
2565 InputMapper::configure(when, config, changes);
2566
2567 if (!changes) { // first time only
2568 mCursorScrollAccumulator.configure(getDevice());
2569
2570 // Configure basic parameters.
2571 configureParameters();
2572
2573 // Configure device mode.
2574 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002575 case Parameters::MODE_POINTER_RELATIVE:
2576 // Should not happen during first time configuration.
2577 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2578 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002579 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002580 case Parameters::MODE_POINTER:
2581 mSource = AINPUT_SOURCE_MOUSE;
2582 mXPrecision = 1.0f;
2583 mYPrecision = 1.0f;
2584 mXScale = 1.0f;
2585 mYScale = 1.0f;
2586 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2587 break;
2588 case Parameters::MODE_NAVIGATION:
2589 mSource = AINPUT_SOURCE_TRACKBALL;
2590 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2591 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2592 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2593 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2594 break;
2595 }
2596
2597 mVWheelScale = 1.0f;
2598 mHWheelScale = 1.0f;
2599 }
2600
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002601 if ((!changes && config->pointerCapture)
2602 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2603 if (config->pointerCapture) {
2604 if (mParameters.mode == Parameters::MODE_POINTER) {
2605 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2606 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2607 // Keep PointerController around in order to preserve the pointer position.
2608 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2609 } else {
2610 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2611 }
2612 } else {
2613 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2614 mParameters.mode = Parameters::MODE_POINTER;
2615 mSource = AINPUT_SOURCE_MOUSE;
2616 } else {
2617 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2618 }
2619 }
2620 bumpGeneration();
2621 if (changes) {
2622 getDevice()->notifyReset(when);
2623 }
2624 }
2625
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2627 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2628 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2629 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2630 }
2631
2632 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002633 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002634 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002635 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002636 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002637 if (internalViewport) {
2638 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002639 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002640 }
2641 bumpGeneration();
2642 }
2643}
2644
2645void CursorInputMapper::configureParameters() {
2646 mParameters.mode = Parameters::MODE_POINTER;
2647 String8 cursorModeString;
2648 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2649 if (cursorModeString == "navigation") {
2650 mParameters.mode = Parameters::MODE_NAVIGATION;
2651 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2652 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2653 }
2654 }
2655
2656 mParameters.orientationAware = false;
2657 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2658 mParameters.orientationAware);
2659
2660 mParameters.hasAssociatedDisplay = false;
2661 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2662 mParameters.hasAssociatedDisplay = true;
2663 }
2664}
2665
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002666void CursorInputMapper::dumpParameters(std::string& dump) {
2667 dump += INDENT3 "Parameters:\n";
2668 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002669 toString(mParameters.hasAssociatedDisplay));
2670
2671 switch (mParameters.mode) {
2672 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002673 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002674 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002675 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002676 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002677 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002678 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002679 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002680 break;
2681 default:
2682 ALOG_ASSERT(false);
2683 }
2684
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002685 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002686 toString(mParameters.orientationAware));
2687}
2688
2689void CursorInputMapper::reset(nsecs_t when) {
2690 mButtonState = 0;
2691 mDownTime = 0;
2692
2693 mPointerVelocityControl.reset();
2694 mWheelXVelocityControl.reset();
2695 mWheelYVelocityControl.reset();
2696
2697 mCursorButtonAccumulator.reset(getDevice());
2698 mCursorMotionAccumulator.reset(getDevice());
2699 mCursorScrollAccumulator.reset(getDevice());
2700
2701 InputMapper::reset(when);
2702}
2703
2704void CursorInputMapper::process(const RawEvent* rawEvent) {
2705 mCursorButtonAccumulator.process(rawEvent);
2706 mCursorMotionAccumulator.process(rawEvent);
2707 mCursorScrollAccumulator.process(rawEvent);
2708
2709 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2710 sync(rawEvent->when);
2711 }
2712}
2713
2714void CursorInputMapper::sync(nsecs_t when) {
2715 int32_t lastButtonState = mButtonState;
2716 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2717 mButtonState = currentButtonState;
2718
2719 bool wasDown = isPointerDown(lastButtonState);
2720 bool down = isPointerDown(currentButtonState);
2721 bool downChanged;
2722 if (!wasDown && down) {
2723 mDownTime = when;
2724 downChanged = true;
2725 } else if (wasDown && !down) {
2726 downChanged = true;
2727 } else {
2728 downChanged = false;
2729 }
2730 nsecs_t downTime = mDownTime;
2731 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002732 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2733 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002734
2735 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2736 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2737 bool moved = deltaX != 0 || deltaY != 0;
2738
2739 // Rotate delta according to orientation if needed.
2740 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2741 && (deltaX != 0.0f || deltaY != 0.0f)) {
2742 rotateDelta(mOrientation, &deltaX, &deltaY);
2743 }
2744
2745 // Move the pointer.
2746 PointerProperties pointerProperties;
2747 pointerProperties.clear();
2748 pointerProperties.id = 0;
2749 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2750
2751 PointerCoords pointerCoords;
2752 pointerCoords.clear();
2753
2754 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2755 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2756 bool scrolled = vscroll != 0 || hscroll != 0;
2757
Yi Kong9b14ac62018-07-17 13:48:38 -07002758 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2759 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002760
2761 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2762
2763 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002764 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002765 if (moved || scrolled || buttonsChanged) {
2766 mPointerController->setPresentation(
2767 PointerControllerInterface::PRESENTATION_POINTER);
2768
2769 if (moved) {
2770 mPointerController->move(deltaX, deltaY);
2771 }
2772
2773 if (buttonsChanged) {
2774 mPointerController->setButtonState(currentButtonState);
2775 }
2776
2777 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2778 }
2779
2780 float x, y;
2781 mPointerController->getPosition(&x, &y);
2782 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2783 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002784 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2785 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002786 displayId = ADISPLAY_ID_DEFAULT;
2787 } else {
2788 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2789 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2790 displayId = ADISPLAY_ID_NONE;
2791 }
2792
2793 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2794
2795 // Moving an external trackball or mouse should wake the device.
2796 // We don't do this for internal cursor devices to prevent them from waking up
2797 // the device in your pocket.
2798 // TODO: Use the input device configuration to control this behavior more finely.
2799 uint32_t policyFlags = 0;
2800 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002801 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 }
2803
2804 // Synthesize key down from buttons if needed.
2805 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002806 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002807
2808 // Send motion event.
2809 if (downChanged || moved || scrolled || buttonsChanged) {
2810 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002811 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002812 int32_t motionEventAction;
2813 if (downChanged) {
2814 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002815 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002816 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2817 } else {
2818 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2819 }
2820
Michael Wright7b159c92015-05-14 14:48:03 +01002821 if (buttonsReleased) {
2822 BitSet32 released(buttonsReleased);
2823 while (!released.isEmpty()) {
2824 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2825 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002826 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002827 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2828 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002829 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002830 mXPrecision, mYPrecision, downTime);
2831 getListener()->notifyMotion(&releaseArgs);
2832 }
2833 }
2834
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002835 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002836 motionEventAction, 0, 0, metaState, currentButtonState,
2837 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002838 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002839 mXPrecision, mYPrecision, downTime);
2840 getListener()->notifyMotion(&args);
2841
Michael Wright7b159c92015-05-14 14:48:03 +01002842 if (buttonsPressed) {
2843 BitSet32 pressed(buttonsPressed);
2844 while (!pressed.isEmpty()) {
2845 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2846 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002847 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002848 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2849 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002850 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002851 mXPrecision, mYPrecision, downTime);
2852 getListener()->notifyMotion(&pressArgs);
2853 }
2854 }
2855
2856 ALOG_ASSERT(buttonState == currentButtonState);
2857
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 // Send hover move after UP to tell the application that the mouse is hovering now.
2859 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002860 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002861 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002862 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002863 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002864 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002865 mXPrecision, mYPrecision, downTime);
2866 getListener()->notifyMotion(&hoverArgs);
2867 }
2868
2869 // Send scroll events.
2870 if (scrolled) {
2871 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2872 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2873
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002874 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002875 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002876 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002877 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002878 mXPrecision, mYPrecision, downTime);
2879 getListener()->notifyMotion(&scrollArgs);
2880 }
2881 }
2882
2883 // Synthesize key up from buttons if needed.
2884 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002885 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002886
2887 mCursorMotionAccumulator.finishSync();
2888 mCursorScrollAccumulator.finishSync();
2889}
2890
2891int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2892 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2893 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2894 } else {
2895 return AKEY_STATE_UNKNOWN;
2896 }
2897}
2898
2899void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002900 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002901 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2902 }
2903}
2904
Prashant Malani1941ff52015-08-11 18:29:28 -07002905// --- RotaryEncoderInputMapper ---
2906
2907RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002908 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002909 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2910}
2911
2912RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2913}
2914
2915uint32_t RotaryEncoderInputMapper::getSources() {
2916 return mSource;
2917}
2918
2919void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2920 InputMapper::populateDeviceInfo(info);
2921
2922 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002923 float res = 0.0f;
2924 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2925 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2926 }
2927 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2928 mScalingFactor)) {
2929 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2930 "default to 1.0!\n");
2931 mScalingFactor = 1.0f;
2932 }
2933 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2934 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002935 }
2936}
2937
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002938void RotaryEncoderInputMapper::dump(std::string& dump) {
2939 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2940 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002941 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2942}
2943
2944void RotaryEncoderInputMapper::configure(nsecs_t when,
2945 const InputReaderConfiguration* config, uint32_t changes) {
2946 InputMapper::configure(when, config, changes);
2947 if (!changes) {
2948 mRotaryEncoderScrollAccumulator.configure(getDevice());
2949 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002950 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002951 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002952 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002953 if (internalViewport) {
2954 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002955 } else {
2956 mOrientation = DISPLAY_ORIENTATION_0;
2957 }
2958 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002959}
2960
2961void RotaryEncoderInputMapper::reset(nsecs_t when) {
2962 mRotaryEncoderScrollAccumulator.reset(getDevice());
2963
2964 InputMapper::reset(when);
2965}
2966
2967void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2968 mRotaryEncoderScrollAccumulator.process(rawEvent);
2969
2970 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2971 sync(rawEvent->when);
2972 }
2973}
2974
2975void RotaryEncoderInputMapper::sync(nsecs_t when) {
2976 PointerCoords pointerCoords;
2977 pointerCoords.clear();
2978
2979 PointerProperties pointerProperties;
2980 pointerProperties.clear();
2981 pointerProperties.id = 0;
2982 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2983
2984 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2985 bool scrolled = scroll != 0;
2986
2987 // This is not a pointer, so it's not associated with a display.
2988 int32_t displayId = ADISPLAY_ID_NONE;
2989
2990 // Moving the rotary encoder should wake the device (if specified).
2991 uint32_t policyFlags = 0;
2992 if (scrolled && getDevice()->isExternal()) {
2993 policyFlags |= POLICY_FLAG_WAKE;
2994 }
2995
Ivan Podogovad437252016-09-29 16:29:55 +01002996 if (mOrientation == DISPLAY_ORIENTATION_180) {
2997 scroll = -scroll;
2998 }
2999
Prashant Malani1941ff52015-08-11 18:29:28 -07003000 // Send motion event.
3001 if (scrolled) {
3002 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003003 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003004
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003005 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07003006 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
3007 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08003008 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07003009 0, 0, 0);
3010 getListener()->notifyMotion(&scrollArgs);
3011 }
3012
3013 mRotaryEncoderScrollAccumulator.finishSync();
3014}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003015
3016// --- TouchInputMapper ---
3017
3018TouchInputMapper::TouchInputMapper(InputDevice* device) :
3019 InputMapper(device),
3020 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3021 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003022 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003023 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3024}
3025
3026TouchInputMapper::~TouchInputMapper() {
3027}
3028
3029uint32_t TouchInputMapper::getSources() {
3030 return mSource;
3031}
3032
3033void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3034 InputMapper::populateDeviceInfo(info);
3035
3036 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3037 info->addMotionRange(mOrientedRanges.x);
3038 info->addMotionRange(mOrientedRanges.y);
3039 info->addMotionRange(mOrientedRanges.pressure);
3040
3041 if (mOrientedRanges.haveSize) {
3042 info->addMotionRange(mOrientedRanges.size);
3043 }
3044
3045 if (mOrientedRanges.haveTouchSize) {
3046 info->addMotionRange(mOrientedRanges.touchMajor);
3047 info->addMotionRange(mOrientedRanges.touchMinor);
3048 }
3049
3050 if (mOrientedRanges.haveToolSize) {
3051 info->addMotionRange(mOrientedRanges.toolMajor);
3052 info->addMotionRange(mOrientedRanges.toolMinor);
3053 }
3054
3055 if (mOrientedRanges.haveOrientation) {
3056 info->addMotionRange(mOrientedRanges.orientation);
3057 }
3058
3059 if (mOrientedRanges.haveDistance) {
3060 info->addMotionRange(mOrientedRanges.distance);
3061 }
3062
3063 if (mOrientedRanges.haveTilt) {
3064 info->addMotionRange(mOrientedRanges.tilt);
3065 }
3066
3067 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3068 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3069 0.0f);
3070 }
3071 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3072 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3073 0.0f);
3074 }
3075 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3076 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3077 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3078 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3079 x.fuzz, x.resolution);
3080 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3081 y.fuzz, y.resolution);
3082 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3083 x.fuzz, x.resolution);
3084 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3085 y.fuzz, y.resolution);
3086 }
3087 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3088 }
3089}
3090
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003091void TouchInputMapper::dump(std::string& dump) {
3092 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003093 dumpParameters(dump);
3094 dumpVirtualKeys(dump);
3095 dumpRawPointerAxes(dump);
3096 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003097 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003098 dumpSurface(dump);
3099
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003100 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3101 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3102 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3103 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3104 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3105 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3106 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3107 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3108 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3109 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3110 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3111 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3112 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3113 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3114 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3115 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3116 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003117
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003118 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3119 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003120 mLastRawState.rawPointerData.pointerCount);
3121 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3122 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003123 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003124 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3125 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3126 "toolType=%d, isHovering=%s\n", i,
3127 pointer.id, pointer.x, pointer.y, pointer.pressure,
3128 pointer.touchMajor, pointer.touchMinor,
3129 pointer.toolMajor, pointer.toolMinor,
3130 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3131 pointer.toolType, toString(pointer.isHovering));
3132 }
3133
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003134 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3135 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003136 mLastCookedState.cookedPointerData.pointerCount);
3137 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3138 const PointerProperties& pointerProperties =
3139 mLastCookedState.cookedPointerData.pointerProperties[i];
3140 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003141 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3143 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3144 "toolType=%d, isHovering=%s\n", i,
3145 pointerProperties.id,
3146 pointerCoords.getX(),
3147 pointerCoords.getY(),
3148 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3149 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3150 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3151 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3152 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3153 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3154 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3155 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3156 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003157 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 }
3159
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003160 dump += INDENT3 "Stylus Fusion:\n";
3161 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003162 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003163 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3164 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003165 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003166 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003167 dumpStylusState(dump, mExternalStylusState);
3168
Michael Wrightd02c5b62014-02-10 15:10:22 -08003169 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003170 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3171 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003172 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003173 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003174 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003175 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003176 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003177 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003178 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003179 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180 mPointerGestureMaxSwipeWidth);
3181 }
3182}
3183
Santos Cordonfa5cf462017-04-05 10:37:00 -07003184const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3185 switch (deviceMode) {
3186 case DEVICE_MODE_DISABLED:
3187 return "disabled";
3188 case DEVICE_MODE_DIRECT:
3189 return "direct";
3190 case DEVICE_MODE_UNSCALED:
3191 return "unscaled";
3192 case DEVICE_MODE_NAVIGATION:
3193 return "navigation";
3194 case DEVICE_MODE_POINTER:
3195 return "pointer";
3196 }
3197 return "unknown";
3198}
3199
Michael Wrightd02c5b62014-02-10 15:10:22 -08003200void TouchInputMapper::configure(nsecs_t when,
3201 const InputReaderConfiguration* config, uint32_t changes) {
3202 InputMapper::configure(when, config, changes);
3203
3204 mConfig = *config;
3205
3206 if (!changes) { // first time only
3207 // Configure basic parameters.
3208 configureParameters();
3209
3210 // Configure common accumulators.
3211 mCursorScrollAccumulator.configure(getDevice());
3212 mTouchButtonAccumulator.configure(getDevice());
3213
3214 // Configure absolute axis information.
3215 configureRawPointerAxes();
3216
3217 // Prepare input device calibration.
3218 parseCalibration();
3219 resolveCalibration();
3220 }
3221
Michael Wright842500e2015-03-13 17:32:02 -07003222 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003223 // Update location calibration to reflect current settings
3224 updateAffineTransformation();
3225 }
3226
Michael Wrightd02c5b62014-02-10 15:10:22 -08003227 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3228 // Update pointer speed.
3229 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3230 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3231 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3232 }
3233
3234 bool resetNeeded = false;
3235 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3236 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003237 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3238 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003239 // Configure device sources, surface dimensions, orientation and
3240 // scaling factors.
3241 configureSurface(when, &resetNeeded);
3242 }
3243
3244 if (changes && resetNeeded) {
3245 // Send reset, unless this is the first time the device has been configured,
3246 // in which case the reader will call reset itself after all mappers are ready.
3247 getDevice()->notifyReset(when);
3248 }
3249}
3250
Michael Wright842500e2015-03-13 17:32:02 -07003251void TouchInputMapper::resolveExternalStylusPresence() {
3252 Vector<InputDeviceInfo> devices;
3253 mContext->getExternalStylusDevices(devices);
3254 mExternalStylusConnected = !devices.isEmpty();
3255
3256 if (!mExternalStylusConnected) {
3257 resetExternalStylus();
3258 }
3259}
3260
Michael Wrightd02c5b62014-02-10 15:10:22 -08003261void TouchInputMapper::configureParameters() {
3262 // Use the pointer presentation mode for devices that do not support distinct
3263 // multitouch. The spot-based presentation relies on being able to accurately
3264 // locate two or more fingers on the touch pad.
3265 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003266 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003267
3268 String8 gestureModeString;
3269 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3270 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003271 if (gestureModeString == "single-touch") {
3272 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3273 } else if (gestureModeString == "multi-touch") {
3274 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003275 } else if (gestureModeString != "default") {
3276 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3277 }
3278 }
3279
3280 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3281 // The device is a touch screen.
3282 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3283 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3284 // The device is a pointing device like a track pad.
3285 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3286 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3287 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3288 // The device is a cursor device with a touch pad attached.
3289 // By default don't use the touch pad to move the pointer.
3290 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3291 } else {
3292 // The device is a touch pad of unknown purpose.
3293 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3294 }
3295
3296 mParameters.hasButtonUnderPad=
3297 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3298
3299 String8 deviceTypeString;
3300 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3301 deviceTypeString)) {
3302 if (deviceTypeString == "touchScreen") {
3303 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3304 } else if (deviceTypeString == "touchPad") {
3305 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3306 } else if (deviceTypeString == "touchNavigation") {
3307 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3308 } else if (deviceTypeString == "pointer") {
3309 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3310 } else if (deviceTypeString != "default") {
3311 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3312 }
3313 }
3314
3315 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3316 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3317 mParameters.orientationAware);
3318
3319 mParameters.hasAssociatedDisplay = false;
3320 mParameters.associatedDisplayIsExternal = false;
3321 if (mParameters.orientationAware
3322 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3323 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3324 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003325 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3326 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003327 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003328 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003329 uniqueDisplayId);
3330 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003331 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003332 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003333 if (getDevice()->getAssociatedDisplayPort()) {
3334 mParameters.hasAssociatedDisplay = true;
3335 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003336
3337 // Initial downs on external touch devices should wake the device.
3338 // Normally we don't do this for internal touch screens to prevent them from waking
3339 // up in your pocket but you can enable it using the input device configuration.
3340 mParameters.wake = getDevice()->isExternal();
3341 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3342 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003343}
3344
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003345void TouchInputMapper::dumpParameters(std::string& dump) {
3346 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347
3348 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003349 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003350 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003351 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003352 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003353 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003354 break;
3355 default:
3356 assert(false);
3357 }
3358
3359 switch (mParameters.deviceType) {
3360 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003361 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003362 break;
3363 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003364 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003365 break;
3366 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003367 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 break;
3369 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003370 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003371 break;
3372 default:
3373 ALOG_ASSERT(false);
3374 }
3375
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003376 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003377 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003378 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003379 toString(mParameters.associatedDisplayIsExternal),
3380 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003381 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003382 toString(mParameters.orientationAware));
3383}
3384
3385void TouchInputMapper::configureRawPointerAxes() {
3386 mRawPointerAxes.clear();
3387}
3388
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003389void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3390 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3392 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3393 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3394 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3395 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3396 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3397 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3398 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3399 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3400 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3401 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3402 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3403 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3404}
3405
Michael Wright842500e2015-03-13 17:32:02 -07003406bool TouchInputMapper::hasExternalStylus() const {
3407 return mExternalStylusConnected;
3408}
3409
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003410/**
3411 * Determine which DisplayViewport to use.
3412 * 1. If display port is specified, return the matching viewport. If matching viewport not
3413 * found, then return.
3414 * 2. If a device has associated display, get the matching viewport by either unique id or by
3415 * the display type (internal or external).
3416 * 3. Otherwise, use a non-display viewport.
3417 */
3418std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3419 if (mParameters.hasAssociatedDisplay) {
3420 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3421 if (displayPort) {
3422 // Find the viewport that contains the same port
3423 std::optional<DisplayViewport> v = mConfig.getDisplayViewportByPort(*displayPort);
3424 if (!v) {
3425 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
3426 "but the corresponding viewport is not found.",
3427 getDeviceName().c_str(), *displayPort);
3428 }
3429 return v;
3430 }
3431
3432 if (!mParameters.uniqueDisplayId.empty()) {
3433 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3434 }
3435
3436 ViewportType viewportTypeToUse;
3437 if (mParameters.associatedDisplayIsExternal) {
3438 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3439 } else {
3440 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3441 }
3442 return mConfig.getDisplayViewportByType(viewportTypeToUse);
3443 }
3444
3445 DisplayViewport newViewport;
3446 // Raw width and height in the natural orientation.
3447 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3448 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3449 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3450 return std::make_optional(newViewport);
3451}
3452
Michael Wrightd02c5b62014-02-10 15:10:22 -08003453void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3454 int32_t oldDeviceMode = mDeviceMode;
3455
Michael Wright842500e2015-03-13 17:32:02 -07003456 resolveExternalStylusPresence();
3457
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 // Determine device mode.
3459 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3460 && mConfig.pointerGesturesEnabled) {
3461 mSource = AINPUT_SOURCE_MOUSE;
3462 mDeviceMode = DEVICE_MODE_POINTER;
3463 if (hasStylus()) {
3464 mSource |= AINPUT_SOURCE_STYLUS;
3465 }
3466 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3467 && mParameters.hasAssociatedDisplay) {
3468 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3469 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003470 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003471 mSource |= AINPUT_SOURCE_STYLUS;
3472 }
Michael Wright2f78b682015-06-12 15:25:08 +01003473 if (hasExternalStylus()) {
3474 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3475 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003476 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3477 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3478 mDeviceMode = DEVICE_MODE_NAVIGATION;
3479 } else {
3480 mSource = AINPUT_SOURCE_TOUCHPAD;
3481 mDeviceMode = DEVICE_MODE_UNSCALED;
3482 }
3483
3484 // Ensure we have valid X and Y axes.
3485 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003486 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003487 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003488 mDeviceMode = DEVICE_MODE_DISABLED;
3489 return;
3490 }
3491
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003492 // Get associated display dimensions.
3493 std::optional<DisplayViewport> newViewport = findViewport();
3494 if (!newViewport) {
3495 ALOGI("Touch device '%s' could not query the properties of its associated "
3496 "display. The device will be inoperable until the display size "
3497 "becomes available.",
3498 getDeviceName().c_str());
3499 mDeviceMode = DEVICE_MODE_DISABLED;
3500 return;
3501 }
3502
Michael Wrightd02c5b62014-02-10 15:10:22 -08003503 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003504 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3505 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003506
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003507 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003508 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003509 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003510
3511 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3512 // Convert rotated viewport to natural surface coordinates.
3513 int32_t naturalLogicalWidth, naturalLogicalHeight;
3514 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3515 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3516 int32_t naturalDeviceWidth, naturalDeviceHeight;
3517 switch (mViewport.orientation) {
3518 case DISPLAY_ORIENTATION_90:
3519 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3520 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3521 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3522 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3523 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3524 naturalPhysicalTop = mViewport.physicalLeft;
3525 naturalDeviceWidth = mViewport.deviceHeight;
3526 naturalDeviceHeight = mViewport.deviceWidth;
3527 break;
3528 case DISPLAY_ORIENTATION_180:
3529 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3530 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3531 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3532 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3533 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3534 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3535 naturalDeviceWidth = mViewport.deviceWidth;
3536 naturalDeviceHeight = mViewport.deviceHeight;
3537 break;
3538 case DISPLAY_ORIENTATION_270:
3539 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3540 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3541 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3542 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3543 naturalPhysicalLeft = mViewport.physicalTop;
3544 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3545 naturalDeviceWidth = mViewport.deviceHeight;
3546 naturalDeviceHeight = mViewport.deviceWidth;
3547 break;
3548 case DISPLAY_ORIENTATION_0:
3549 default:
3550 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3551 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3552 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3553 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3554 naturalPhysicalLeft = mViewport.physicalLeft;
3555 naturalPhysicalTop = mViewport.physicalTop;
3556 naturalDeviceWidth = mViewport.deviceWidth;
3557 naturalDeviceHeight = mViewport.deviceHeight;
3558 break;
3559 }
3560
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003561 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3562 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3563 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3564 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3565 }
3566
Michael Wright358bcc72018-08-21 04:01:07 +01003567 mPhysicalWidth = naturalPhysicalWidth;
3568 mPhysicalHeight = naturalPhysicalHeight;
3569 mPhysicalLeft = naturalPhysicalLeft;
3570 mPhysicalTop = naturalPhysicalTop;
3571
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3573 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3574 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3575 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3576
3577 mSurfaceOrientation = mParameters.orientationAware ?
3578 mViewport.orientation : DISPLAY_ORIENTATION_0;
3579 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003580 mPhysicalWidth = rawWidth;
3581 mPhysicalHeight = rawHeight;
3582 mPhysicalLeft = 0;
3583 mPhysicalTop = 0;
3584
Michael Wrightd02c5b62014-02-10 15:10:22 -08003585 mSurfaceWidth = rawWidth;
3586 mSurfaceHeight = rawHeight;
3587 mSurfaceLeft = 0;
3588 mSurfaceTop = 0;
3589 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3590 }
3591 }
3592
3593 // If moving between pointer modes, need to reset some state.
3594 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3595 if (deviceModeChanged) {
3596 mOrientedRanges.clear();
3597 }
3598
3599 // Create pointer controller if needed.
3600 if (mDeviceMode == DEVICE_MODE_POINTER ||
3601 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003602 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003603 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3604 }
3605 } else {
3606 mPointerController.clear();
3607 }
3608
3609 if (viewportChanged || deviceModeChanged) {
3610 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3611 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003612 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003613 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3614
3615 // Configure X and Y factors.
3616 mXScale = float(mSurfaceWidth) / rawWidth;
3617 mYScale = float(mSurfaceHeight) / rawHeight;
3618 mXTranslate = -mSurfaceLeft;
3619 mYTranslate = -mSurfaceTop;
3620 mXPrecision = 1.0f / mXScale;
3621 mYPrecision = 1.0f / mYScale;
3622
3623 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3624 mOrientedRanges.x.source = mSource;
3625 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3626 mOrientedRanges.y.source = mSource;
3627
3628 configureVirtualKeys();
3629
3630 // Scale factor for terms that are not oriented in a particular axis.
3631 // If the pixels are square then xScale == yScale otherwise we fake it
3632 // by choosing an average.
3633 mGeometricScale = avg(mXScale, mYScale);
3634
3635 // Size of diagonal axis.
3636 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3637
3638 // Size factors.
3639 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3640 if (mRawPointerAxes.touchMajor.valid
3641 && mRawPointerAxes.touchMajor.maxValue != 0) {
3642 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3643 } else if (mRawPointerAxes.toolMajor.valid
3644 && mRawPointerAxes.toolMajor.maxValue != 0) {
3645 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3646 } else {
3647 mSizeScale = 0.0f;
3648 }
3649
3650 mOrientedRanges.haveTouchSize = true;
3651 mOrientedRanges.haveToolSize = true;
3652 mOrientedRanges.haveSize = true;
3653
3654 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3655 mOrientedRanges.touchMajor.source = mSource;
3656 mOrientedRanges.touchMajor.min = 0;
3657 mOrientedRanges.touchMajor.max = diagonalSize;
3658 mOrientedRanges.touchMajor.flat = 0;
3659 mOrientedRanges.touchMajor.fuzz = 0;
3660 mOrientedRanges.touchMajor.resolution = 0;
3661
3662 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3663 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3664
3665 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3666 mOrientedRanges.toolMajor.source = mSource;
3667 mOrientedRanges.toolMajor.min = 0;
3668 mOrientedRanges.toolMajor.max = diagonalSize;
3669 mOrientedRanges.toolMajor.flat = 0;
3670 mOrientedRanges.toolMajor.fuzz = 0;
3671 mOrientedRanges.toolMajor.resolution = 0;
3672
3673 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3674 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3675
3676 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3677 mOrientedRanges.size.source = mSource;
3678 mOrientedRanges.size.min = 0;
3679 mOrientedRanges.size.max = 1.0;
3680 mOrientedRanges.size.flat = 0;
3681 mOrientedRanges.size.fuzz = 0;
3682 mOrientedRanges.size.resolution = 0;
3683 } else {
3684 mSizeScale = 0.0f;
3685 }
3686
3687 // Pressure factors.
3688 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003689 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003690 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3691 || mCalibration.pressureCalibration
3692 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3693 if (mCalibration.havePressureScale) {
3694 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003695 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003696 } else if (mRawPointerAxes.pressure.valid
3697 && mRawPointerAxes.pressure.maxValue != 0) {
3698 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3699 }
3700 }
3701
3702 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3703 mOrientedRanges.pressure.source = mSource;
3704 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003705 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003706 mOrientedRanges.pressure.flat = 0;
3707 mOrientedRanges.pressure.fuzz = 0;
3708 mOrientedRanges.pressure.resolution = 0;
3709
3710 // Tilt
3711 mTiltXCenter = 0;
3712 mTiltXScale = 0;
3713 mTiltYCenter = 0;
3714 mTiltYScale = 0;
3715 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3716 if (mHaveTilt) {
3717 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3718 mRawPointerAxes.tiltX.maxValue);
3719 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3720 mRawPointerAxes.tiltY.maxValue);
3721 mTiltXScale = M_PI / 180;
3722 mTiltYScale = M_PI / 180;
3723
3724 mOrientedRanges.haveTilt = true;
3725
3726 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3727 mOrientedRanges.tilt.source = mSource;
3728 mOrientedRanges.tilt.min = 0;
3729 mOrientedRanges.tilt.max = M_PI_2;
3730 mOrientedRanges.tilt.flat = 0;
3731 mOrientedRanges.tilt.fuzz = 0;
3732 mOrientedRanges.tilt.resolution = 0;
3733 }
3734
3735 // Orientation
3736 mOrientationScale = 0;
3737 if (mHaveTilt) {
3738 mOrientedRanges.haveOrientation = true;
3739
3740 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3741 mOrientedRanges.orientation.source = mSource;
3742 mOrientedRanges.orientation.min = -M_PI;
3743 mOrientedRanges.orientation.max = M_PI;
3744 mOrientedRanges.orientation.flat = 0;
3745 mOrientedRanges.orientation.fuzz = 0;
3746 mOrientedRanges.orientation.resolution = 0;
3747 } else if (mCalibration.orientationCalibration !=
3748 Calibration::ORIENTATION_CALIBRATION_NONE) {
3749 if (mCalibration.orientationCalibration
3750 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3751 if (mRawPointerAxes.orientation.valid) {
3752 if (mRawPointerAxes.orientation.maxValue > 0) {
3753 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3754 } else if (mRawPointerAxes.orientation.minValue < 0) {
3755 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3756 } else {
3757 mOrientationScale = 0;
3758 }
3759 }
3760 }
3761
3762 mOrientedRanges.haveOrientation = true;
3763
3764 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3765 mOrientedRanges.orientation.source = mSource;
3766 mOrientedRanges.orientation.min = -M_PI_2;
3767 mOrientedRanges.orientation.max = M_PI_2;
3768 mOrientedRanges.orientation.flat = 0;
3769 mOrientedRanges.orientation.fuzz = 0;
3770 mOrientedRanges.orientation.resolution = 0;
3771 }
3772
3773 // Distance
3774 mDistanceScale = 0;
3775 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3776 if (mCalibration.distanceCalibration
3777 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3778 if (mCalibration.haveDistanceScale) {
3779 mDistanceScale = mCalibration.distanceScale;
3780 } else {
3781 mDistanceScale = 1.0f;
3782 }
3783 }
3784
3785 mOrientedRanges.haveDistance = true;
3786
3787 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3788 mOrientedRanges.distance.source = mSource;
3789 mOrientedRanges.distance.min =
3790 mRawPointerAxes.distance.minValue * mDistanceScale;
3791 mOrientedRanges.distance.max =
3792 mRawPointerAxes.distance.maxValue * mDistanceScale;
3793 mOrientedRanges.distance.flat = 0;
3794 mOrientedRanges.distance.fuzz =
3795 mRawPointerAxes.distance.fuzz * mDistanceScale;
3796 mOrientedRanges.distance.resolution = 0;
3797 }
3798
3799 // Compute oriented precision, scales and ranges.
3800 // Note that the maximum value reported is an inclusive maximum value so it is one
3801 // unit less than the total width or height of surface.
3802 switch (mSurfaceOrientation) {
3803 case DISPLAY_ORIENTATION_90:
3804 case DISPLAY_ORIENTATION_270:
3805 mOrientedXPrecision = mYPrecision;
3806 mOrientedYPrecision = mXPrecision;
3807
3808 mOrientedRanges.x.min = mYTranslate;
3809 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3810 mOrientedRanges.x.flat = 0;
3811 mOrientedRanges.x.fuzz = 0;
3812 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3813
3814 mOrientedRanges.y.min = mXTranslate;
3815 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3816 mOrientedRanges.y.flat = 0;
3817 mOrientedRanges.y.fuzz = 0;
3818 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3819 break;
3820
3821 default:
3822 mOrientedXPrecision = mXPrecision;
3823 mOrientedYPrecision = mYPrecision;
3824
3825 mOrientedRanges.x.min = mXTranslate;
3826 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3827 mOrientedRanges.x.flat = 0;
3828 mOrientedRanges.x.fuzz = 0;
3829 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3830
3831 mOrientedRanges.y.min = mYTranslate;
3832 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3833 mOrientedRanges.y.flat = 0;
3834 mOrientedRanges.y.fuzz = 0;
3835 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3836 break;
3837 }
3838
Jason Gerecke71b16e82014-03-10 09:47:59 -07003839 // Location
3840 updateAffineTransformation();
3841
Michael Wrightd02c5b62014-02-10 15:10:22 -08003842 if (mDeviceMode == DEVICE_MODE_POINTER) {
3843 // Compute pointer gesture detection parameters.
3844 float rawDiagonal = hypotf(rawWidth, rawHeight);
3845 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3846
3847 // Scale movements such that one whole swipe of the touch pad covers a
3848 // given area relative to the diagonal size of the display when no acceleration
3849 // is applied.
3850 // Assume that the touch pad has a square aspect ratio such that movements in
3851 // X and Y of the same number of raw units cover the same physical distance.
3852 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3853 * displayDiagonal / rawDiagonal;
3854 mPointerYMovementScale = mPointerXMovementScale;
3855
3856 // Scale zooms to cover a smaller range of the display than movements do.
3857 // This value determines the area around the pointer that is affected by freeform
3858 // pointer gestures.
3859 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3860 * displayDiagonal / rawDiagonal;
3861 mPointerYZoomScale = mPointerXZoomScale;
3862
3863 // Max width between pointers to detect a swipe gesture is more than some fraction
3864 // of the diagonal axis of the touch pad. Touches that are wider than this are
3865 // translated into freeform gestures.
3866 mPointerGestureMaxSwipeWidth =
3867 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3868
3869 // Abort current pointer usages because the state has changed.
3870 abortPointerUsage(when, 0 /*policyFlags*/);
3871 }
3872
3873 // Inform the dispatcher about the changes.
3874 *outResetNeeded = true;
3875 bumpGeneration();
3876 }
3877}
3878
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003879void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003880 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003881 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3882 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3883 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3884 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003885 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3886 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3887 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3888 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003889 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003890}
3891
3892void TouchInputMapper::configureVirtualKeys() {
3893 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3894 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3895
3896 mVirtualKeys.clear();
3897
3898 if (virtualKeyDefinitions.size() == 0) {
3899 return;
3900 }
3901
3902 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3903
3904 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3905 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003906 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3907 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908
3909 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3910 const VirtualKeyDefinition& virtualKeyDefinition =
3911 virtualKeyDefinitions[i];
3912
3913 mVirtualKeys.add();
3914 VirtualKey& virtualKey = mVirtualKeys.editTop();
3915
3916 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3917 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003918 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003919 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003920 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3921 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003922 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3923 virtualKey.scanCode);
3924 mVirtualKeys.pop(); // drop the key
3925 continue;
3926 }
3927
3928 virtualKey.keyCode = keyCode;
3929 virtualKey.flags = flags;
3930
3931 // convert the key definition's display coordinates into touch coordinates for a hit box
3932 int32_t halfWidth = virtualKeyDefinition.width / 2;
3933 int32_t halfHeight = virtualKeyDefinition.height / 2;
3934
3935 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3936 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3937 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3938 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3939 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3940 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3941 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3942 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3943 }
3944}
3945
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003946void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003948 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003949
3950 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3951 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003952 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003953 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3954 i, virtualKey.scanCode, virtualKey.keyCode,
3955 virtualKey.hitLeft, virtualKey.hitRight,
3956 virtualKey.hitTop, virtualKey.hitBottom);
3957 }
3958 }
3959}
3960
3961void TouchInputMapper::parseCalibration() {
3962 const PropertyMap& in = getDevice()->getConfiguration();
3963 Calibration& out = mCalibration;
3964
3965 // Size
3966 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3967 String8 sizeCalibrationString;
3968 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3969 if (sizeCalibrationString == "none") {
3970 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3971 } else if (sizeCalibrationString == "geometric") {
3972 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3973 } else if (sizeCalibrationString == "diameter") {
3974 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3975 } else if (sizeCalibrationString == "box") {
3976 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3977 } else if (sizeCalibrationString == "area") {
3978 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3979 } else if (sizeCalibrationString != "default") {
3980 ALOGW("Invalid value for touch.size.calibration: '%s'",
3981 sizeCalibrationString.string());
3982 }
3983 }
3984
3985 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3986 out.sizeScale);
3987 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3988 out.sizeBias);
3989 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3990 out.sizeIsSummed);
3991
3992 // Pressure
3993 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3994 String8 pressureCalibrationString;
3995 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3996 if (pressureCalibrationString == "none") {
3997 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3998 } else if (pressureCalibrationString == "physical") {
3999 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4000 } else if (pressureCalibrationString == "amplitude") {
4001 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4002 } else if (pressureCalibrationString != "default") {
4003 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
4004 pressureCalibrationString.string());
4005 }
4006 }
4007
4008 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
4009 out.pressureScale);
4010
4011 // Orientation
4012 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4013 String8 orientationCalibrationString;
4014 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4015 if (orientationCalibrationString == "none") {
4016 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4017 } else if (orientationCalibrationString == "interpolated") {
4018 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4019 } else if (orientationCalibrationString == "vector") {
4020 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4021 } else if (orientationCalibrationString != "default") {
4022 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
4023 orientationCalibrationString.string());
4024 }
4025 }
4026
4027 // Distance
4028 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4029 String8 distanceCalibrationString;
4030 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4031 if (distanceCalibrationString == "none") {
4032 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4033 } else if (distanceCalibrationString == "scaled") {
4034 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4035 } else if (distanceCalibrationString != "default") {
4036 ALOGW("Invalid value for touch.distance.calibration: '%s'",
4037 distanceCalibrationString.string());
4038 }
4039 }
4040
4041 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
4042 out.distanceScale);
4043
4044 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4045 String8 coverageCalibrationString;
4046 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4047 if (coverageCalibrationString == "none") {
4048 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4049 } else if (coverageCalibrationString == "box") {
4050 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4051 } else if (coverageCalibrationString != "default") {
4052 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4053 coverageCalibrationString.string());
4054 }
4055 }
4056}
4057
4058void TouchInputMapper::resolveCalibration() {
4059 // Size
4060 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4061 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4062 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4063 }
4064 } else {
4065 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4066 }
4067
4068 // Pressure
4069 if (mRawPointerAxes.pressure.valid) {
4070 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4071 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4072 }
4073 } else {
4074 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4075 }
4076
4077 // Orientation
4078 if (mRawPointerAxes.orientation.valid) {
4079 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4080 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4081 }
4082 } else {
4083 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4084 }
4085
4086 // Distance
4087 if (mRawPointerAxes.distance.valid) {
4088 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4089 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4090 }
4091 } else {
4092 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4093 }
4094
4095 // Coverage
4096 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4097 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4098 }
4099}
4100
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004101void TouchInputMapper::dumpCalibration(std::string& dump) {
4102 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004103
4104 // Size
4105 switch (mCalibration.sizeCalibration) {
4106 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004107 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004108 break;
4109 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004110 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 break;
4112 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004113 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004114 break;
4115 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004116 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004117 break;
4118 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004119 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004120 break;
4121 default:
4122 ALOG_ASSERT(false);
4123 }
4124
4125 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004126 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004127 mCalibration.sizeScale);
4128 }
4129
4130 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004131 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004132 mCalibration.sizeBias);
4133 }
4134
4135 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004136 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004137 toString(mCalibration.sizeIsSummed));
4138 }
4139
4140 // Pressure
4141 switch (mCalibration.pressureCalibration) {
4142 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004143 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004144 break;
4145 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004146 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004147 break;
4148 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004149 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004150 break;
4151 default:
4152 ALOG_ASSERT(false);
4153 }
4154
4155 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004156 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004157 mCalibration.pressureScale);
4158 }
4159
4160 // Orientation
4161 switch (mCalibration.orientationCalibration) {
4162 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004163 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004164 break;
4165 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004166 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004167 break;
4168 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004169 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 break;
4171 default:
4172 ALOG_ASSERT(false);
4173 }
4174
4175 // Distance
4176 switch (mCalibration.distanceCalibration) {
4177 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004178 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 break;
4180 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004181 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004182 break;
4183 default:
4184 ALOG_ASSERT(false);
4185 }
4186
4187 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004188 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004189 mCalibration.distanceScale);
4190 }
4191
4192 switch (mCalibration.coverageCalibration) {
4193 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004194 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004195 break;
4196 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004197 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 break;
4199 default:
4200 ALOG_ASSERT(false);
4201 }
4202}
4203
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004204void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4205 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004206
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004207 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4208 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4209 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4210 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4211 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4212 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004213}
4214
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004215void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004216 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4217 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004218}
4219
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220void TouchInputMapper::reset(nsecs_t when) {
4221 mCursorButtonAccumulator.reset(getDevice());
4222 mCursorScrollAccumulator.reset(getDevice());
4223 mTouchButtonAccumulator.reset(getDevice());
4224
4225 mPointerVelocityControl.reset();
4226 mWheelXVelocityControl.reset();
4227 mWheelYVelocityControl.reset();
4228
Michael Wright842500e2015-03-13 17:32:02 -07004229 mRawStatesPending.clear();
4230 mCurrentRawState.clear();
4231 mCurrentCookedState.clear();
4232 mLastRawState.clear();
4233 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004234 mPointerUsage = POINTER_USAGE_NONE;
4235 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004236 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004237 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004238 mDownTime = 0;
4239
4240 mCurrentVirtualKey.down = false;
4241
4242 mPointerGesture.reset();
4243 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004244 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004245
Yi Kong9b14ac62018-07-17 13:48:38 -07004246 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4248 mPointerController->clearSpots();
4249 }
4250
4251 InputMapper::reset(when);
4252}
4253
Michael Wright842500e2015-03-13 17:32:02 -07004254void TouchInputMapper::resetExternalStylus() {
4255 mExternalStylusState.clear();
4256 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004257 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004258 mExternalStylusDataPending = false;
4259}
4260
Michael Wright43fd19f2015-04-21 19:02:58 +01004261void TouchInputMapper::clearStylusDataPendingFlags() {
4262 mExternalStylusDataPending = false;
4263 mExternalStylusFusionTimeout = LLONG_MAX;
4264}
4265
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266void TouchInputMapper::process(const RawEvent* rawEvent) {
4267 mCursorButtonAccumulator.process(rawEvent);
4268 mCursorScrollAccumulator.process(rawEvent);
4269 mTouchButtonAccumulator.process(rawEvent);
4270
4271 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4272 sync(rawEvent->when);
4273 }
4274}
4275
4276void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004277 const RawState* last = mRawStatesPending.isEmpty() ?
4278 &mCurrentRawState : &mRawStatesPending.top();
4279
4280 // Push a new state.
4281 mRawStatesPending.push();
4282 RawState* next = &mRawStatesPending.editTop();
4283 next->clear();
4284 next->when = when;
4285
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004287 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004288 | mCursorButtonAccumulator.getButtonState();
4289
Michael Wright842500e2015-03-13 17:32:02 -07004290 // Sync scroll
4291 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4292 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004293 mCursorScrollAccumulator.finishSync();
4294
Michael Wright842500e2015-03-13 17:32:02 -07004295 // Sync touch
4296 syncTouch(when, next);
4297
4298 // Assign pointer ids.
4299 if (!mHavePointerIds) {
4300 assignPointerIds(last, next);
4301 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004302
4303#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004304 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4305 "hovering ids 0x%08x -> 0x%08x",
4306 last->rawPointerData.pointerCount,
4307 next->rawPointerData.pointerCount,
4308 last->rawPointerData.touchingIdBits.value,
4309 next->rawPointerData.touchingIdBits.value,
4310 last->rawPointerData.hoveringIdBits.value,
4311 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004312#endif
4313
Michael Wright842500e2015-03-13 17:32:02 -07004314 processRawTouches(false /*timeout*/);
4315}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004316
Michael Wright842500e2015-03-13 17:32:02 -07004317void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004318 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4319 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004320 mCurrentRawState.clear();
4321 mRawStatesPending.clear();
4322 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004323 }
4324
Michael Wright842500e2015-03-13 17:32:02 -07004325 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4326 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4327 // touching the current state will only observe the events that have been dispatched to the
4328 // rest of the pipeline.
4329 const size_t N = mRawStatesPending.size();
4330 size_t count;
4331 for(count = 0; count < N; count++) {
4332 const RawState& next = mRawStatesPending[count];
4333
4334 // A failure to assign the stylus id means that we're waiting on stylus data
4335 // and so should defer the rest of the pipeline.
4336 if (assignExternalStylusId(next, timeout)) {
4337 break;
4338 }
4339
4340 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004341 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004342 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004343 if (mCurrentRawState.when < mLastRawState.when) {
4344 mCurrentRawState.when = mLastRawState.when;
4345 }
Michael Wright842500e2015-03-13 17:32:02 -07004346 cookAndDispatch(mCurrentRawState.when);
4347 }
4348 if (count != 0) {
4349 mRawStatesPending.removeItemsAt(0, count);
4350 }
4351
Michael Wright842500e2015-03-13 17:32:02 -07004352 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004353 if (timeout) {
4354 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4355 clearStylusDataPendingFlags();
4356 mCurrentRawState.copyFrom(mLastRawState);
4357#if DEBUG_STYLUS_FUSION
4358 ALOGD("Timeout expired, synthesizing event with new stylus data");
4359#endif
4360 cookAndDispatch(when);
4361 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4362 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4363 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4364 }
Michael Wright842500e2015-03-13 17:32:02 -07004365 }
4366}
4367
4368void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4369 // Always start with a clean state.
4370 mCurrentCookedState.clear();
4371
4372 // Apply stylus buttons to current raw state.
4373 applyExternalStylusButtonState(when);
4374
4375 // Handle policy on initial down or hover events.
4376 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4377 && mCurrentRawState.rawPointerData.pointerCount != 0;
4378
4379 uint32_t policyFlags = 0;
4380 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4381 if (initialDown || buttonsPressed) {
4382 // If this is a touch screen, hide the pointer on an initial down.
4383 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4384 getContext()->fadePointer();
4385 }
4386
4387 if (mParameters.wake) {
4388 policyFlags |= POLICY_FLAG_WAKE;
4389 }
4390 }
4391
4392 // Consume raw off-screen touches before cooking pointer data.
4393 // If touches are consumed, subsequent code will not receive any pointer data.
4394 if (consumeRawTouches(when, policyFlags)) {
4395 mCurrentRawState.rawPointerData.clear();
4396 }
4397
4398 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4399 // with cooked pointer data that has the same ids and indices as the raw data.
4400 // The following code can use either the raw or cooked data, as needed.
4401 cookPointerData();
4402
4403 // Apply stylus pressure to current cooked state.
4404 applyExternalStylusTouchState(when);
4405
4406 // Synthesize key down from raw buttons if needed.
4407 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004408 mViewport.displayId, policyFlags,
4409 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004410
4411 // Dispatch the touches either directly or by translation through a pointer on screen.
4412 if (mDeviceMode == DEVICE_MODE_POINTER) {
4413 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4414 !idBits.isEmpty(); ) {
4415 uint32_t id = idBits.clearFirstMarkedBit();
4416 const RawPointerData::Pointer& pointer =
4417 mCurrentRawState.rawPointerData.pointerForId(id);
4418 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4419 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4420 mCurrentCookedState.stylusIdBits.markBit(id);
4421 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4422 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4423 mCurrentCookedState.fingerIdBits.markBit(id);
4424 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4425 mCurrentCookedState.mouseIdBits.markBit(id);
4426 }
4427 }
4428 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4429 !idBits.isEmpty(); ) {
4430 uint32_t id = idBits.clearFirstMarkedBit();
4431 const RawPointerData::Pointer& pointer =
4432 mCurrentRawState.rawPointerData.pointerForId(id);
4433 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4434 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4435 mCurrentCookedState.stylusIdBits.markBit(id);
4436 }
4437 }
4438
4439 // Stylus takes precedence over all tools, then mouse, then finger.
4440 PointerUsage pointerUsage = mPointerUsage;
4441 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4442 mCurrentCookedState.mouseIdBits.clear();
4443 mCurrentCookedState.fingerIdBits.clear();
4444 pointerUsage = POINTER_USAGE_STYLUS;
4445 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4446 mCurrentCookedState.fingerIdBits.clear();
4447 pointerUsage = POINTER_USAGE_MOUSE;
4448 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4449 isPointerDown(mCurrentRawState.buttonState)) {
4450 pointerUsage = POINTER_USAGE_GESTURES;
4451 }
4452
4453 dispatchPointerUsage(when, policyFlags, pointerUsage);
4454 } else {
4455 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004456 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004457 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4458 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4459
4460 mPointerController->setButtonState(mCurrentRawState.buttonState);
4461 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4462 mCurrentCookedState.cookedPointerData.idToIndex,
4463 mCurrentCookedState.cookedPointerData.touchingIdBits);
4464 }
4465
Michael Wright8e812822015-06-22 16:18:21 +01004466 if (!mCurrentMotionAborted) {
4467 dispatchButtonRelease(when, policyFlags);
4468 dispatchHoverExit(when, policyFlags);
4469 dispatchTouches(when, policyFlags);
4470 dispatchHoverEnterAndMove(when, policyFlags);
4471 dispatchButtonPress(when, policyFlags);
4472 }
4473
4474 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4475 mCurrentMotionAborted = false;
4476 }
Michael Wright842500e2015-03-13 17:32:02 -07004477 }
4478
4479 // Synthesize key up from raw buttons if needed.
4480 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004481 mViewport.displayId, policyFlags,
4482 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004483
4484 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004485 mCurrentRawState.rawVScroll = 0;
4486 mCurrentRawState.rawHScroll = 0;
4487
4488 // Copy current touch to last touch in preparation for the next cycle.
4489 mLastRawState.copyFrom(mCurrentRawState);
4490 mLastCookedState.copyFrom(mCurrentCookedState);
4491}
4492
4493void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004494 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004495 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4496 }
4497}
4498
4499void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004500 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4501 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004502
Michael Wright53dca3a2015-04-23 17:39:53 +01004503 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4504 float pressure = mExternalStylusState.pressure;
4505 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4506 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4507 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4508 }
4509 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4510 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4511
4512 PointerProperties& properties =
4513 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004514 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4515 properties.toolType = mExternalStylusState.toolType;
4516 }
4517 }
4518}
4519
4520bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4521 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4522 return false;
4523 }
4524
4525 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4526 && state.rawPointerData.pointerCount != 0;
4527 if (initialDown) {
4528 if (mExternalStylusState.pressure != 0.0f) {
4529#if DEBUG_STYLUS_FUSION
4530 ALOGD("Have both stylus and touch data, beginning fusion");
4531#endif
4532 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4533 } else if (timeout) {
4534#if DEBUG_STYLUS_FUSION
4535 ALOGD("Timeout expired, assuming touch is not a stylus.");
4536#endif
4537 resetExternalStylus();
4538 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004539 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4540 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004541 }
4542#if DEBUG_STYLUS_FUSION
4543 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004544 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004545#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004546 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004547 return true;
4548 }
4549 }
4550
4551 // Check if the stylus pointer has gone up.
4552 if (mExternalStylusId != -1 &&
4553 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4554#if DEBUG_STYLUS_FUSION
4555 ALOGD("Stylus pointer is going up");
4556#endif
4557 mExternalStylusId = -1;
4558 }
4559
4560 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004561}
4562
4563void TouchInputMapper::timeoutExpired(nsecs_t when) {
4564 if (mDeviceMode == DEVICE_MODE_POINTER) {
4565 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4566 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4567 }
Michael Wright842500e2015-03-13 17:32:02 -07004568 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004569 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004570 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004571 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4572 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004573 }
4574 }
4575}
4576
4577void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004578 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004579 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004580 // We're either in the middle of a fused stream of data or we're waiting on data before
4581 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4582 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004583 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004584 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004585 }
4586}
4587
4588bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4589 // Check for release of a virtual key.
4590 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004591 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004592 // Pointer went up while virtual key was down.
4593 mCurrentVirtualKey.down = false;
4594 if (!mCurrentVirtualKey.ignored) {
4595#if DEBUG_VIRTUAL_KEYS
4596 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4597 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4598#endif
4599 dispatchVirtualKey(when, policyFlags,
4600 AKEY_EVENT_ACTION_UP,
4601 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4602 }
4603 return true;
4604 }
4605
Michael Wright842500e2015-03-13 17:32:02 -07004606 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4607 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4608 const RawPointerData::Pointer& pointer =
4609 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004610 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4611 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4612 // Pointer is still within the space of the virtual key.
4613 return true;
4614 }
4615 }
4616
4617 // Pointer left virtual key area or another pointer also went down.
4618 // Send key cancellation but do not consume the touch yet.
4619 // This is useful when the user swipes through from the virtual key area
4620 // into the main display surface.
4621 mCurrentVirtualKey.down = false;
4622 if (!mCurrentVirtualKey.ignored) {
4623#if DEBUG_VIRTUAL_KEYS
4624 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4625 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4626#endif
4627 dispatchVirtualKey(when, policyFlags,
4628 AKEY_EVENT_ACTION_UP,
4629 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4630 | AKEY_EVENT_FLAG_CANCELED);
4631 }
4632 }
4633
Michael Wright842500e2015-03-13 17:32:02 -07004634 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4635 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004636 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004637 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4638 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004639 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4640 // If exactly one pointer went down, check for virtual key hit.
4641 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004642 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004643 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4644 if (virtualKey) {
4645 mCurrentVirtualKey.down = true;
4646 mCurrentVirtualKey.downTime = when;
4647 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4648 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4649 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4650 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4651
4652 if (!mCurrentVirtualKey.ignored) {
4653#if DEBUG_VIRTUAL_KEYS
4654 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4655 mCurrentVirtualKey.keyCode,
4656 mCurrentVirtualKey.scanCode);
4657#endif
4658 dispatchVirtualKey(when, policyFlags,
4659 AKEY_EVENT_ACTION_DOWN,
4660 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4661 }
4662 }
4663 }
4664 return true;
4665 }
4666 }
4667
4668 // Disable all virtual key touches that happen within a short time interval of the
4669 // most recent touch within the screen area. The idea is to filter out stray
4670 // virtual key presses when interacting with the touch screen.
4671 //
4672 // Problems we're trying to solve:
4673 //
4674 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4675 // virtual key area that is implemented by a separate touch panel and accidentally
4676 // triggers a virtual key.
4677 //
4678 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4679 // area and accidentally triggers a virtual key. This often happens when virtual keys
4680 // are layed out below the screen near to where the on screen keyboard's space bar
4681 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004682 if (mConfig.virtualKeyQuietTime > 0 &&
4683 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004684 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4685 }
4686 return false;
4687}
4688
4689void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4690 int32_t keyEventAction, int32_t keyEventFlags) {
4691 int32_t keyCode = mCurrentVirtualKey.keyCode;
4692 int32_t scanCode = mCurrentVirtualKey.scanCode;
4693 nsecs_t downTime = mCurrentVirtualKey.downTime;
4694 int32_t metaState = mContext->getGlobalMetaState();
4695 policyFlags |= POLICY_FLAG_VIRTUAL;
4696
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004697 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4698 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004699 getListener()->notifyKey(&args);
4700}
4701
Michael Wright8e812822015-06-22 16:18:21 +01004702void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4703 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4704 if (!currentIdBits.isEmpty()) {
4705 int32_t metaState = getContext()->getGlobalMetaState();
4706 int32_t buttonState = mCurrentCookedState.buttonState;
4707 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4708 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004709 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004710 mCurrentCookedState.cookedPointerData.pointerProperties,
4711 mCurrentCookedState.cookedPointerData.pointerCoords,
4712 mCurrentCookedState.cookedPointerData.idToIndex,
4713 currentIdBits, -1,
4714 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4715 mCurrentMotionAborted = true;
4716 }
4717}
4718
Michael Wrightd02c5b62014-02-10 15:10:22 -08004719void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004720 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4721 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004722 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004723 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004724
4725 if (currentIdBits == lastIdBits) {
4726 if (!currentIdBits.isEmpty()) {
4727 // No pointer id changes so this is a move event.
4728 // The listener takes care of batching moves so we don't have to deal with that here.
4729 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004730 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004731 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004732 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004733 mCurrentCookedState.cookedPointerData.pointerProperties,
4734 mCurrentCookedState.cookedPointerData.pointerCoords,
4735 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004736 currentIdBits, -1,
4737 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4738 }
4739 } else {
4740 // There may be pointers going up and pointers going down and pointers moving
4741 // all at the same time.
4742 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4743 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4744 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4745 BitSet32 dispatchedIdBits(lastIdBits.value);
4746
4747 // Update last coordinates of pointers that have moved so that we observe the new
4748 // pointer positions at the same time as other pointers that have just gone up.
4749 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004750 mCurrentCookedState.cookedPointerData.pointerProperties,
4751 mCurrentCookedState.cookedPointerData.pointerCoords,
4752 mCurrentCookedState.cookedPointerData.idToIndex,
4753 mLastCookedState.cookedPointerData.pointerProperties,
4754 mLastCookedState.cookedPointerData.pointerCoords,
4755 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004756 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004757 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004758 moveNeeded = true;
4759 }
4760
4761 // Dispatch pointer up events.
4762 while (!upIdBits.isEmpty()) {
4763 uint32_t upId = upIdBits.clearFirstMarkedBit();
4764
4765 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004766 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004767 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004768 mLastCookedState.cookedPointerData.pointerProperties,
4769 mLastCookedState.cookedPointerData.pointerCoords,
4770 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004771 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004772 dispatchedIdBits.clearBit(upId);
4773 }
4774
4775 // Dispatch move events if any of the remaining pointers moved from their old locations.
4776 // Although applications receive new locations as part of individual pointer up
4777 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004778 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004779 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4780 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004781 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004782 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004783 mCurrentCookedState.cookedPointerData.pointerProperties,
4784 mCurrentCookedState.cookedPointerData.pointerCoords,
4785 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004786 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 }
4788
4789 // Dispatch pointer down events using the new pointer locations.
4790 while (!downIdBits.isEmpty()) {
4791 uint32_t downId = downIdBits.clearFirstMarkedBit();
4792 dispatchedIdBits.markBit(downId);
4793
4794 if (dispatchedIdBits.count() == 1) {
4795 // First pointer is going down. Set down time.
4796 mDownTime = when;
4797 }
4798
4799 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004800 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004801 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004802 mCurrentCookedState.cookedPointerData.pointerProperties,
4803 mCurrentCookedState.cookedPointerData.pointerCoords,
4804 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004805 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004806 }
4807 }
4808}
4809
4810void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4811 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004812 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4813 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004814 int32_t metaState = getContext()->getGlobalMetaState();
4815 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004816 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004817 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004818 mLastCookedState.cookedPointerData.pointerProperties,
4819 mLastCookedState.cookedPointerData.pointerCoords,
4820 mLastCookedState.cookedPointerData.idToIndex,
4821 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004822 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4823 mSentHoverEnter = false;
4824 }
4825}
4826
4827void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004828 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4829 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004830 int32_t metaState = getContext()->getGlobalMetaState();
4831 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004832 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004833 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004834 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004835 mCurrentCookedState.cookedPointerData.pointerProperties,
4836 mCurrentCookedState.cookedPointerData.pointerCoords,
4837 mCurrentCookedState.cookedPointerData.idToIndex,
4838 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4840 mSentHoverEnter = true;
4841 }
4842
4843 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004844 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004845 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004846 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004847 mCurrentCookedState.cookedPointerData.pointerProperties,
4848 mCurrentCookedState.cookedPointerData.pointerCoords,
4849 mCurrentCookedState.cookedPointerData.idToIndex,
4850 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004851 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4852 }
4853}
4854
Michael Wright7b159c92015-05-14 14:48:03 +01004855void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4856 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4857 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4858 const int32_t metaState = getContext()->getGlobalMetaState();
4859 int32_t buttonState = mLastCookedState.buttonState;
4860 while (!releasedButtons.isEmpty()) {
4861 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4862 buttonState &= ~actionButton;
4863 dispatchMotion(when, policyFlags, mSource,
4864 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4865 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004866 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004867 mCurrentCookedState.cookedPointerData.pointerProperties,
4868 mCurrentCookedState.cookedPointerData.pointerCoords,
4869 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4870 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4871 }
4872}
4873
4874void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4875 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4876 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4877 const int32_t metaState = getContext()->getGlobalMetaState();
4878 int32_t buttonState = mLastCookedState.buttonState;
4879 while (!pressedButtons.isEmpty()) {
4880 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4881 buttonState |= actionButton;
4882 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4883 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004884 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004885 mCurrentCookedState.cookedPointerData.pointerProperties,
4886 mCurrentCookedState.cookedPointerData.pointerCoords,
4887 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4888 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4889 }
4890}
4891
4892const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4893 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4894 return cookedPointerData.touchingIdBits;
4895 }
4896 return cookedPointerData.hoveringIdBits;
4897}
4898
Michael Wrightd02c5b62014-02-10 15:10:22 -08004899void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004900 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004901
Michael Wright842500e2015-03-13 17:32:02 -07004902 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004903 mCurrentCookedState.deviceTimestamp =
4904 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004905 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4906 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4907 mCurrentRawState.rawPointerData.hoveringIdBits;
4908 mCurrentCookedState.cookedPointerData.touchingIdBits =
4909 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004910
Michael Wright7b159c92015-05-14 14:48:03 +01004911 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4912 mCurrentCookedState.buttonState = 0;
4913 } else {
4914 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4915 }
4916
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917 // Walk through the the active pointers and map device coordinates onto
4918 // surface coordinates and adjust for display orientation.
4919 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004920 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004921
4922 // Size
4923 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4924 switch (mCalibration.sizeCalibration) {
4925 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4926 case Calibration::SIZE_CALIBRATION_DIAMETER:
4927 case Calibration::SIZE_CALIBRATION_BOX:
4928 case Calibration::SIZE_CALIBRATION_AREA:
4929 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4930 touchMajor = in.touchMajor;
4931 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4932 toolMajor = in.toolMajor;
4933 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4934 size = mRawPointerAxes.touchMinor.valid
4935 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4936 } else if (mRawPointerAxes.touchMajor.valid) {
4937 toolMajor = touchMajor = in.touchMajor;
4938 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4939 ? in.touchMinor : in.touchMajor;
4940 size = mRawPointerAxes.touchMinor.valid
4941 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4942 } else if (mRawPointerAxes.toolMajor.valid) {
4943 touchMajor = toolMajor = in.toolMajor;
4944 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4945 ? in.toolMinor : in.toolMajor;
4946 size = mRawPointerAxes.toolMinor.valid
4947 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4948 } else {
4949 ALOG_ASSERT(false, "No touch or tool axes. "
4950 "Size calibration should have been resolved to NONE.");
4951 touchMajor = 0;
4952 touchMinor = 0;
4953 toolMajor = 0;
4954 toolMinor = 0;
4955 size = 0;
4956 }
4957
4958 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004959 uint32_t touchingCount =
4960 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004961 if (touchingCount > 1) {
4962 touchMajor /= touchingCount;
4963 touchMinor /= touchingCount;
4964 toolMajor /= touchingCount;
4965 toolMinor /= touchingCount;
4966 size /= touchingCount;
4967 }
4968 }
4969
4970 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4971 touchMajor *= mGeometricScale;
4972 touchMinor *= mGeometricScale;
4973 toolMajor *= mGeometricScale;
4974 toolMinor *= mGeometricScale;
4975 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4976 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4977 touchMinor = touchMajor;
4978 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4979 toolMinor = toolMajor;
4980 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4981 touchMinor = touchMajor;
4982 toolMinor = toolMajor;
4983 }
4984
4985 mCalibration.applySizeScaleAndBias(&touchMajor);
4986 mCalibration.applySizeScaleAndBias(&touchMinor);
4987 mCalibration.applySizeScaleAndBias(&toolMajor);
4988 mCalibration.applySizeScaleAndBias(&toolMinor);
4989 size *= mSizeScale;
4990 break;
4991 default:
4992 touchMajor = 0;
4993 touchMinor = 0;
4994 toolMajor = 0;
4995 toolMinor = 0;
4996 size = 0;
4997 break;
4998 }
4999
5000 // Pressure
5001 float pressure;
5002 switch (mCalibration.pressureCalibration) {
5003 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5004 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5005 pressure = in.pressure * mPressureScale;
5006 break;
5007 default:
5008 pressure = in.isHovering ? 0 : 1;
5009 break;
5010 }
5011
5012 // Tilt and Orientation
5013 float tilt;
5014 float orientation;
5015 if (mHaveTilt) {
5016 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5017 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5018 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5019 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5020 } else {
5021 tilt = 0;
5022
5023 switch (mCalibration.orientationCalibration) {
5024 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5025 orientation = in.orientation * mOrientationScale;
5026 break;
5027 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5028 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5029 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5030 if (c1 != 0 || c2 != 0) {
5031 orientation = atan2f(c1, c2) * 0.5f;
5032 float confidence = hypotf(c1, c2);
5033 float scale = 1.0f + confidence / 16.0f;
5034 touchMajor *= scale;
5035 touchMinor /= scale;
5036 toolMajor *= scale;
5037 toolMinor /= scale;
5038 } else {
5039 orientation = 0;
5040 }
5041 break;
5042 }
5043 default:
5044 orientation = 0;
5045 }
5046 }
5047
5048 // Distance
5049 float distance;
5050 switch (mCalibration.distanceCalibration) {
5051 case Calibration::DISTANCE_CALIBRATION_SCALED:
5052 distance = in.distance * mDistanceScale;
5053 break;
5054 default:
5055 distance = 0;
5056 }
5057
5058 // Coverage
5059 int32_t rawLeft, rawTop, rawRight, rawBottom;
5060 switch (mCalibration.coverageCalibration) {
5061 case Calibration::COVERAGE_CALIBRATION_BOX:
5062 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5063 rawRight = in.toolMinor & 0x0000ffff;
5064 rawBottom = in.toolMajor & 0x0000ffff;
5065 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5066 break;
5067 default:
5068 rawLeft = rawTop = rawRight = rawBottom = 0;
5069 break;
5070 }
5071
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005072 // Adjust X,Y coords for device calibration
5073 // TODO: Adjust coverage coords?
5074 float xTransformed = in.x, yTransformed = in.y;
5075 mAffineTransform.applyTo(xTransformed, yTransformed);
5076
5077 // Adjust X, Y, and coverage coords for surface orientation.
5078 float x, y;
5079 float left, top, right, bottom;
5080
Michael Wrightd02c5b62014-02-10 15:10:22 -08005081 switch (mSurfaceOrientation) {
5082 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005083 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5084 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005085 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5086 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5087 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5088 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5089 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005090 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005091 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5092 }
5093 break;
5094 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005095 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005096 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005097 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5098 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005099 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5100 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5101 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005102 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005103 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5104 }
5105 break;
5106 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005107 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005108 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005109 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5110 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005111 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5112 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5113 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005114 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005115 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5116 }
5117 break;
5118 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005119 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5120 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005121 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5122 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5123 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5124 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5125 break;
5126 }
5127
5128 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005129 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005130 out.clear();
5131 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5132 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5133 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5134 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5135 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5136 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5137 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5138 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5139 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5140 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5141 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5142 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5143 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5144 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5145 } else {
5146 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5147 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5148 }
5149
5150 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005151 PointerProperties& properties =
5152 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005153 uint32_t id = in.id;
5154 properties.clear();
5155 properties.id = id;
5156 properties.toolType = in.toolType;
5157
5158 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005159 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005160 }
5161}
5162
5163void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5164 PointerUsage pointerUsage) {
5165 if (pointerUsage != mPointerUsage) {
5166 abortPointerUsage(when, policyFlags);
5167 mPointerUsage = pointerUsage;
5168 }
5169
5170 switch (mPointerUsage) {
5171 case POINTER_USAGE_GESTURES:
5172 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5173 break;
5174 case POINTER_USAGE_STYLUS:
5175 dispatchPointerStylus(when, policyFlags);
5176 break;
5177 case POINTER_USAGE_MOUSE:
5178 dispatchPointerMouse(when, policyFlags);
5179 break;
5180 default:
5181 break;
5182 }
5183}
5184
5185void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5186 switch (mPointerUsage) {
5187 case POINTER_USAGE_GESTURES:
5188 abortPointerGestures(when, policyFlags);
5189 break;
5190 case POINTER_USAGE_STYLUS:
5191 abortPointerStylus(when, policyFlags);
5192 break;
5193 case POINTER_USAGE_MOUSE:
5194 abortPointerMouse(when, policyFlags);
5195 break;
5196 default:
5197 break;
5198 }
5199
5200 mPointerUsage = POINTER_USAGE_NONE;
5201}
5202
5203void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5204 bool isTimeout) {
5205 // Update current gesture coordinates.
5206 bool cancelPreviousGesture, finishPreviousGesture;
5207 bool sendEvents = preparePointerGestures(when,
5208 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5209 if (!sendEvents) {
5210 return;
5211 }
5212 if (finishPreviousGesture) {
5213 cancelPreviousGesture = false;
5214 }
5215
5216 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005217 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5218 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 if (finishPreviousGesture || cancelPreviousGesture) {
5220 mPointerController->clearSpots();
5221 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005222
5223 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5224 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5225 mPointerGesture.currentGestureIdToIndex,
5226 mPointerGesture.currentGestureIdBits);
5227 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005228 } else {
5229 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5230 }
5231
5232 // Show or hide the pointer if needed.
5233 switch (mPointerGesture.currentGestureMode) {
5234 case PointerGesture::NEUTRAL:
5235 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005236 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5237 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005238 // Remind the user of where the pointer is after finishing a gesture with spots.
5239 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5240 }
5241 break;
5242 case PointerGesture::TAP:
5243 case PointerGesture::TAP_DRAG:
5244 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5245 case PointerGesture::HOVER:
5246 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005247 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005248 // Unfade the pointer when the current gesture manipulates the
5249 // area directly under the pointer.
5250 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5251 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 case PointerGesture::FREEFORM:
5253 // Fade the pointer when the current gesture manipulates a different
5254 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005255 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5257 } else {
5258 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5259 }
5260 break;
5261 }
5262
5263 // Send events!
5264 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005265 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005266
5267 // Update last coordinates of pointers that have moved so that we observe the new
5268 // pointer positions at the same time as other pointers that have just gone up.
5269 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5270 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5271 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5272 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5273 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5274 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5275 bool moveNeeded = false;
5276 if (down && !cancelPreviousGesture && !finishPreviousGesture
5277 && !mPointerGesture.lastGestureIdBits.isEmpty()
5278 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5279 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5280 & mPointerGesture.lastGestureIdBits.value);
5281 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5282 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5283 mPointerGesture.lastGestureProperties,
5284 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5285 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005286 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287 moveNeeded = true;
5288 }
5289 }
5290
5291 // Send motion events for all pointers that went up or were canceled.
5292 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5293 if (!dispatchedGestureIdBits.isEmpty()) {
5294 if (cancelPreviousGesture) {
5295 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005296 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005297 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005298 mPointerGesture.lastGestureProperties,
5299 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005300 dispatchedGestureIdBits, -1, 0,
5301 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302
5303 dispatchedGestureIdBits.clear();
5304 } else {
5305 BitSet32 upGestureIdBits;
5306 if (finishPreviousGesture) {
5307 upGestureIdBits = dispatchedGestureIdBits;
5308 } else {
5309 upGestureIdBits.value = dispatchedGestureIdBits.value
5310 & ~mPointerGesture.currentGestureIdBits.value;
5311 }
5312 while (!upGestureIdBits.isEmpty()) {
5313 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5314
5315 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005316 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005317 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005318 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005319 mPointerGesture.lastGestureProperties,
5320 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5321 dispatchedGestureIdBits, id,
5322 0, 0, mPointerGesture.downTime);
5323
5324 dispatchedGestureIdBits.clearBit(id);
5325 }
5326 }
5327 }
5328
5329 // Send motion events for all pointers that moved.
5330 if (moveNeeded) {
5331 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005332 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005333 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005334 mPointerGesture.currentGestureProperties,
5335 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5336 dispatchedGestureIdBits, -1,
5337 0, 0, mPointerGesture.downTime);
5338 }
5339
5340 // Send motion events for all pointers that went down.
5341 if (down) {
5342 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5343 & ~dispatchedGestureIdBits.value);
5344 while (!downGestureIdBits.isEmpty()) {
5345 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5346 dispatchedGestureIdBits.markBit(id);
5347
5348 if (dispatchedGestureIdBits.count() == 1) {
5349 mPointerGesture.downTime = when;
5350 }
5351
5352 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005353 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005354 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 mPointerGesture.currentGestureProperties,
5356 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5357 dispatchedGestureIdBits, id,
5358 0, 0, mPointerGesture.downTime);
5359 }
5360 }
5361
5362 // Send motion events for hover.
5363 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5364 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005365 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005366 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005367 mPointerGesture.currentGestureProperties,
5368 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5369 mPointerGesture.currentGestureIdBits, -1,
5370 0, 0, mPointerGesture.downTime);
5371 } else if (dispatchedGestureIdBits.isEmpty()
5372 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5373 // Synthesize a hover move event after all pointers go up to indicate that
5374 // the pointer is hovering again even if the user is not currently touching
5375 // the touch pad. This ensures that a view will receive a fresh hover enter
5376 // event after a tap.
5377 float x, y;
5378 mPointerController->getPosition(&x, &y);
5379
5380 PointerProperties pointerProperties;
5381 pointerProperties.clear();
5382 pointerProperties.id = 0;
5383 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5384
5385 PointerCoords pointerCoords;
5386 pointerCoords.clear();
5387 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5388 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5389
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005390 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005391 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005392 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005393 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005394 0, 0, mPointerGesture.downTime);
5395 getListener()->notifyMotion(&args);
5396 }
5397
5398 // Update state.
5399 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5400 if (!down) {
5401 mPointerGesture.lastGestureIdBits.clear();
5402 } else {
5403 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5404 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5405 uint32_t id = idBits.clearFirstMarkedBit();
5406 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5407 mPointerGesture.lastGestureProperties[index].copyFrom(
5408 mPointerGesture.currentGestureProperties[index]);
5409 mPointerGesture.lastGestureCoords[index].copyFrom(
5410 mPointerGesture.currentGestureCoords[index]);
5411 mPointerGesture.lastGestureIdToIndex[id] = index;
5412 }
5413 }
5414}
5415
5416void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5417 // Cancel previously dispatches pointers.
5418 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5419 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005420 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005421 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005422 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005423 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005424 mPointerGesture.lastGestureProperties,
5425 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5426 mPointerGesture.lastGestureIdBits, -1,
5427 0, 0, mPointerGesture.downTime);
5428 }
5429
5430 // Reset the current pointer gesture.
5431 mPointerGesture.reset();
5432 mPointerVelocityControl.reset();
5433
5434 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005435 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005436 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5437 mPointerController->clearSpots();
5438 }
5439}
5440
5441bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5442 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5443 *outCancelPreviousGesture = false;
5444 *outFinishPreviousGesture = false;
5445
5446 // Handle TAP timeout.
5447 if (isTimeout) {
5448#if DEBUG_GESTURES
5449 ALOGD("Gestures: Processing timeout");
5450#endif
5451
5452 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5453 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5454 // The tap/drag timeout has not yet expired.
5455 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5456 + mConfig.pointerGestureTapDragInterval);
5457 } else {
5458 // The tap is finished.
5459#if DEBUG_GESTURES
5460 ALOGD("Gestures: TAP finished");
5461#endif
5462 *outFinishPreviousGesture = true;
5463
5464 mPointerGesture.activeGestureId = -1;
5465 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5466 mPointerGesture.currentGestureIdBits.clear();
5467
5468 mPointerVelocityControl.reset();
5469 return true;
5470 }
5471 }
5472
5473 // We did not handle this timeout.
5474 return false;
5475 }
5476
Michael Wright842500e2015-03-13 17:32:02 -07005477 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5478 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005479
5480 // Update the velocity tracker.
5481 {
5482 VelocityTracker::Position positions[MAX_POINTERS];
5483 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005484 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005485 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005486 const RawPointerData::Pointer& pointer =
5487 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005488 positions[count].x = pointer.x * mPointerXMovementScale;
5489 positions[count].y = pointer.y * mPointerYMovementScale;
5490 }
5491 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005492 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005493 }
5494
5495 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5496 // to NEUTRAL, then we should not generate tap event.
5497 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5498 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5499 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5500 mPointerGesture.resetTap();
5501 }
5502
5503 // Pick a new active touch id if needed.
5504 // Choose an arbitrary pointer that just went down, if there is one.
5505 // Otherwise choose an arbitrary remaining pointer.
5506 // This guarantees we always have an active touch id when there is at least one pointer.
5507 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005508 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5509 int32_t activeTouchId = lastActiveTouchId;
5510 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005511 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005513 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005514 mPointerGesture.firstTouchTime = when;
5515 }
Michael Wright842500e2015-03-13 17:32:02 -07005516 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005517 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005518 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005519 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 } else {
5521 activeTouchId = mPointerGesture.activeTouchId = -1;
5522 }
5523 }
5524
5525 // Determine whether we are in quiet time.
5526 bool isQuietTime = false;
5527 if (activeTouchId < 0) {
5528 mPointerGesture.resetQuietTime();
5529 } else {
5530 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5531 if (!isQuietTime) {
5532 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5533 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5534 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5535 && currentFingerCount < 2) {
5536 // Enter quiet time when exiting swipe or freeform state.
5537 // This is to prevent accidentally entering the hover state and flinging the
5538 // pointer when finishing a swipe and there is still one pointer left onscreen.
5539 isQuietTime = true;
5540 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5541 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005542 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005543 // Enter quiet time when releasing the button and there are still two or more
5544 // fingers down. This may indicate that one finger was used to press the button
5545 // but it has not gone up yet.
5546 isQuietTime = true;
5547 }
5548 if (isQuietTime) {
5549 mPointerGesture.quietTime = when;
5550 }
5551 }
5552 }
5553
5554 // Switch states based on button and pointer state.
5555 if (isQuietTime) {
5556 // Case 1: Quiet time. (QUIET)
5557#if DEBUG_GESTURES
5558 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5559 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5560#endif
5561 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5562 *outFinishPreviousGesture = true;
5563 }
5564
5565 mPointerGesture.activeGestureId = -1;
5566 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5567 mPointerGesture.currentGestureIdBits.clear();
5568
5569 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005570 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5572 // The pointer follows the active touch point.
5573 // Emit DOWN, MOVE, UP events at the pointer location.
5574 //
5575 // Only the active touch matters; other fingers are ignored. This policy helps
5576 // to handle the case where the user places a second finger on the touch pad
5577 // to apply the necessary force to depress an integrated button below the surface.
5578 // We don't want the second finger to be delivered to applications.
5579 //
5580 // For this to work well, we need to make sure to track the pointer that is really
5581 // active. If the user first puts one finger down to click then adds another
5582 // finger to drag then the active pointer should switch to the finger that is
5583 // being dragged.
5584#if DEBUG_GESTURES
5585 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5586 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5587#endif
5588 // Reset state when just starting.
5589 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5590 *outFinishPreviousGesture = true;
5591 mPointerGesture.activeGestureId = 0;
5592 }
5593
5594 // Switch pointers if needed.
5595 // Find the fastest pointer and follow it.
5596 if (activeTouchId >= 0 && currentFingerCount > 1) {
5597 int32_t bestId = -1;
5598 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005599 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005600 uint32_t id = idBits.clearFirstMarkedBit();
5601 float vx, vy;
5602 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5603 float speed = hypotf(vx, vy);
5604 if (speed > bestSpeed) {
5605 bestId = id;
5606 bestSpeed = speed;
5607 }
5608 }
5609 }
5610 if (bestId >= 0 && bestId != activeTouchId) {
5611 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612#if DEBUG_GESTURES
5613 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5614 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5615#endif
5616 }
5617 }
5618
Jun Mukaifa1706a2015-12-03 01:14:46 -08005619 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005620 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005621 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005622 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005623 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005624 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005625 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5626 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005627
5628 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5629 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5630
5631 // Move the pointer using a relative motion.
5632 // When using spots, the click will occur at the position of the anchor
5633 // spot and all other spots will move there.
5634 mPointerController->move(deltaX, deltaY);
5635 } else {
5636 mPointerVelocityControl.reset();
5637 }
5638
5639 float x, y;
5640 mPointerController->getPosition(&x, &y);
5641
5642 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5643 mPointerGesture.currentGestureIdBits.clear();
5644 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5645 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5646 mPointerGesture.currentGestureProperties[0].clear();
5647 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5648 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5649 mPointerGesture.currentGestureCoords[0].clear();
5650 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5651 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5652 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5653 } else if (currentFingerCount == 0) {
5654 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5655 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5656 *outFinishPreviousGesture = true;
5657 }
5658
5659 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5660 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5661 bool tapped = false;
5662 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5663 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5664 && lastFingerCount == 1) {
5665 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5666 float x, y;
5667 mPointerController->getPosition(&x, &y);
5668 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5669 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5670#if DEBUG_GESTURES
5671 ALOGD("Gestures: TAP");
5672#endif
5673
5674 mPointerGesture.tapUpTime = when;
5675 getContext()->requestTimeoutAtTime(when
5676 + mConfig.pointerGestureTapDragInterval);
5677
5678 mPointerGesture.activeGestureId = 0;
5679 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5680 mPointerGesture.currentGestureIdBits.clear();
5681 mPointerGesture.currentGestureIdBits.markBit(
5682 mPointerGesture.activeGestureId);
5683 mPointerGesture.currentGestureIdToIndex[
5684 mPointerGesture.activeGestureId] = 0;
5685 mPointerGesture.currentGestureProperties[0].clear();
5686 mPointerGesture.currentGestureProperties[0].id =
5687 mPointerGesture.activeGestureId;
5688 mPointerGesture.currentGestureProperties[0].toolType =
5689 AMOTION_EVENT_TOOL_TYPE_FINGER;
5690 mPointerGesture.currentGestureCoords[0].clear();
5691 mPointerGesture.currentGestureCoords[0].setAxisValue(
5692 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5693 mPointerGesture.currentGestureCoords[0].setAxisValue(
5694 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5695 mPointerGesture.currentGestureCoords[0].setAxisValue(
5696 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5697
5698 tapped = true;
5699 } else {
5700#if DEBUG_GESTURES
5701 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5702 x - mPointerGesture.tapX,
5703 y - mPointerGesture.tapY);
5704#endif
5705 }
5706 } else {
5707#if DEBUG_GESTURES
5708 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5709 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5710 (when - mPointerGesture.tapDownTime) * 0.000001f);
5711 } else {
5712 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5713 }
5714#endif
5715 }
5716 }
5717
5718 mPointerVelocityControl.reset();
5719
5720 if (!tapped) {
5721#if DEBUG_GESTURES
5722 ALOGD("Gestures: NEUTRAL");
5723#endif
5724 mPointerGesture.activeGestureId = -1;
5725 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5726 mPointerGesture.currentGestureIdBits.clear();
5727 }
5728 } else if (currentFingerCount == 1) {
5729 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5730 // The pointer follows the active touch point.
5731 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5732 // When in TAP_DRAG, emit MOVE events at the pointer location.
5733 ALOG_ASSERT(activeTouchId >= 0);
5734
5735 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5736 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5737 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5738 float x, y;
5739 mPointerController->getPosition(&x, &y);
5740 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5741 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5742 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5743 } else {
5744#if DEBUG_GESTURES
5745 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5746 x - mPointerGesture.tapX,
5747 y - mPointerGesture.tapY);
5748#endif
5749 }
5750 } else {
5751#if DEBUG_GESTURES
5752 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5753 (when - mPointerGesture.tapUpTime) * 0.000001f);
5754#endif
5755 }
5756 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5757 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5758 }
5759
Jun Mukaifa1706a2015-12-03 01:14:46 -08005760 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005761 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005762 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005763 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005764 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005765 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005766 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5767 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005768
5769 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5770 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5771
5772 // Move the pointer using a relative motion.
5773 // When using spots, the hover or drag will occur at the position of the anchor spot.
5774 mPointerController->move(deltaX, deltaY);
5775 } else {
5776 mPointerVelocityControl.reset();
5777 }
5778
5779 bool down;
5780 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5781#if DEBUG_GESTURES
5782 ALOGD("Gestures: TAP_DRAG");
5783#endif
5784 down = true;
5785 } else {
5786#if DEBUG_GESTURES
5787 ALOGD("Gestures: HOVER");
5788#endif
5789 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5790 *outFinishPreviousGesture = true;
5791 }
5792 mPointerGesture.activeGestureId = 0;
5793 down = false;
5794 }
5795
5796 float x, y;
5797 mPointerController->getPosition(&x, &y);
5798
5799 mPointerGesture.currentGestureIdBits.clear();
5800 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5801 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5802 mPointerGesture.currentGestureProperties[0].clear();
5803 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5804 mPointerGesture.currentGestureProperties[0].toolType =
5805 AMOTION_EVENT_TOOL_TYPE_FINGER;
5806 mPointerGesture.currentGestureCoords[0].clear();
5807 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5808 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5809 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5810 down ? 1.0f : 0.0f);
5811
5812 if (lastFingerCount == 0 && currentFingerCount != 0) {
5813 mPointerGesture.resetTap();
5814 mPointerGesture.tapDownTime = when;
5815 mPointerGesture.tapX = x;
5816 mPointerGesture.tapY = y;
5817 }
5818 } else {
5819 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5820 // We need to provide feedback for each finger that goes down so we cannot wait
5821 // for the fingers to move before deciding what to do.
5822 //
5823 // The ambiguous case is deciding what to do when there are two fingers down but they
5824 // have not moved enough to determine whether they are part of a drag or part of a
5825 // freeform gesture, or just a press or long-press at the pointer location.
5826 //
5827 // When there are two fingers we start with the PRESS hypothesis and we generate a
5828 // down at the pointer location.
5829 //
5830 // When the two fingers move enough or when additional fingers are added, we make
5831 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5832 ALOG_ASSERT(activeTouchId >= 0);
5833
5834 bool settled = when >= mPointerGesture.firstTouchTime
5835 + mConfig.pointerGestureMultitouchSettleInterval;
5836 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5837 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5838 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5839 *outFinishPreviousGesture = true;
5840 } else if (!settled && currentFingerCount > lastFingerCount) {
5841 // Additional pointers have gone down but not yet settled.
5842 // Reset the gesture.
5843#if DEBUG_GESTURES
5844 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5845 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5846 + mConfig.pointerGestureMultitouchSettleInterval - when)
5847 * 0.000001f);
5848#endif
5849 *outCancelPreviousGesture = true;
5850 } else {
5851 // Continue previous gesture.
5852 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5853 }
5854
5855 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5856 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5857 mPointerGesture.activeGestureId = 0;
5858 mPointerGesture.referenceIdBits.clear();
5859 mPointerVelocityControl.reset();
5860
5861 // Use the centroid and pointer location as the reference points for the gesture.
5862#if DEBUG_GESTURES
5863 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5864 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5865 + mConfig.pointerGestureMultitouchSettleInterval - when)
5866 * 0.000001f);
5867#endif
Michael Wright842500e2015-03-13 17:32:02 -07005868 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005869 &mPointerGesture.referenceTouchX,
5870 &mPointerGesture.referenceTouchY);
5871 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5872 &mPointerGesture.referenceGestureY);
5873 }
5874
5875 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005876 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005877 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5878 uint32_t id = idBits.clearFirstMarkedBit();
5879 mPointerGesture.referenceDeltas[id].dx = 0;
5880 mPointerGesture.referenceDeltas[id].dy = 0;
5881 }
Michael Wright842500e2015-03-13 17:32:02 -07005882 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005883
5884 // Add delta for all fingers and calculate a common movement delta.
5885 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005886 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5887 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5889 bool first = (idBits == commonIdBits);
5890 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005891 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5892 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005893 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5894 delta.dx += cpd.x - lpd.x;
5895 delta.dy += cpd.y - lpd.y;
5896
5897 if (first) {
5898 commonDeltaX = delta.dx;
5899 commonDeltaY = delta.dy;
5900 } else {
5901 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5902 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5903 }
5904 }
5905
5906 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5907 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5908 float dist[MAX_POINTER_ID + 1];
5909 int32_t distOverThreshold = 0;
5910 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5911 uint32_t id = idBits.clearFirstMarkedBit();
5912 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5913 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5914 delta.dy * mPointerYZoomScale);
5915 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5916 distOverThreshold += 1;
5917 }
5918 }
5919
5920 // Only transition when at least two pointers have moved further than
5921 // the minimum distance threshold.
5922 if (distOverThreshold >= 2) {
5923 if (currentFingerCount > 2) {
5924 // There are more than two pointers, switch to FREEFORM.
5925#if DEBUG_GESTURES
5926 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5927 currentFingerCount);
5928#endif
5929 *outCancelPreviousGesture = true;
5930 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5931 } else {
5932 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005933 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005934 uint32_t id1 = idBits.clearFirstMarkedBit();
5935 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005936 const RawPointerData::Pointer& p1 =
5937 mCurrentRawState.rawPointerData.pointerForId(id1);
5938 const RawPointerData::Pointer& p2 =
5939 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005940 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5941 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5942 // There are two pointers but they are too far apart for a SWIPE,
5943 // switch to FREEFORM.
5944#if DEBUG_GESTURES
5945 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5946 mutualDistance, mPointerGestureMaxSwipeWidth);
5947#endif
5948 *outCancelPreviousGesture = true;
5949 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5950 } else {
5951 // There are two pointers. Wait for both pointers to start moving
5952 // before deciding whether this is a SWIPE or FREEFORM gesture.
5953 float dist1 = dist[id1];
5954 float dist2 = dist[id2];
5955 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5956 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5957 // Calculate the dot product of the displacement vectors.
5958 // When the vectors are oriented in approximately the same direction,
5959 // the angle betweeen them is near zero and the cosine of the angle
5960 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5961 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5962 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5963 float dx1 = delta1.dx * mPointerXZoomScale;
5964 float dy1 = delta1.dy * mPointerYZoomScale;
5965 float dx2 = delta2.dx * mPointerXZoomScale;
5966 float dy2 = delta2.dy * mPointerYZoomScale;
5967 float dot = dx1 * dx2 + dy1 * dy2;
5968 float cosine = dot / (dist1 * dist2); // denominator always > 0
5969 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5970 // Pointers are moving in the same direction. Switch to SWIPE.
5971#if DEBUG_GESTURES
5972 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5973 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5974 "cosine %0.3f >= %0.3f",
5975 dist1, mConfig.pointerGestureMultitouchMinDistance,
5976 dist2, mConfig.pointerGestureMultitouchMinDistance,
5977 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5978#endif
5979 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5980 } else {
5981 // Pointers are moving in different directions. Switch to FREEFORM.
5982#if DEBUG_GESTURES
5983 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5984 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5985 "cosine %0.3f < %0.3f",
5986 dist1, mConfig.pointerGestureMultitouchMinDistance,
5987 dist2, mConfig.pointerGestureMultitouchMinDistance,
5988 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5989#endif
5990 *outCancelPreviousGesture = true;
5991 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5992 }
5993 }
5994 }
5995 }
5996 }
5997 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5998 // Switch from SWIPE to FREEFORM if additional pointers go down.
5999 // Cancel previous gesture.
6000 if (currentFingerCount > 2) {
6001#if DEBUG_GESTURES
6002 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
6003 currentFingerCount);
6004#endif
6005 *outCancelPreviousGesture = true;
6006 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6007 }
6008 }
6009
6010 // Move the reference points based on the overall group motion of the fingers
6011 // except in PRESS mode while waiting for a transition to occur.
6012 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
6013 && (commonDeltaX || commonDeltaY)) {
6014 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
6015 uint32_t id = idBits.clearFirstMarkedBit();
6016 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6017 delta.dx = 0;
6018 delta.dy = 0;
6019 }
6020
6021 mPointerGesture.referenceTouchX += commonDeltaX;
6022 mPointerGesture.referenceTouchY += commonDeltaY;
6023
6024 commonDeltaX *= mPointerXMovementScale;
6025 commonDeltaY *= mPointerYMovementScale;
6026
6027 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6028 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6029
6030 mPointerGesture.referenceGestureX += commonDeltaX;
6031 mPointerGesture.referenceGestureY += commonDeltaY;
6032 }
6033
6034 // Report gestures.
6035 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
6036 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6037 // PRESS or SWIPE mode.
6038#if DEBUG_GESTURES
6039 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
6040 "activeGestureId=%d, currentTouchPointerCount=%d",
6041 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6042#endif
6043 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6044
6045 mPointerGesture.currentGestureIdBits.clear();
6046 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6047 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6048 mPointerGesture.currentGestureProperties[0].clear();
6049 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6050 mPointerGesture.currentGestureProperties[0].toolType =
6051 AMOTION_EVENT_TOOL_TYPE_FINGER;
6052 mPointerGesture.currentGestureCoords[0].clear();
6053 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6054 mPointerGesture.referenceGestureX);
6055 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6056 mPointerGesture.referenceGestureY);
6057 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6058 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6059 // FREEFORM mode.
6060#if DEBUG_GESTURES
6061 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6062 "activeGestureId=%d, currentTouchPointerCount=%d",
6063 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6064#endif
6065 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6066
6067 mPointerGesture.currentGestureIdBits.clear();
6068
6069 BitSet32 mappedTouchIdBits;
6070 BitSet32 usedGestureIdBits;
6071 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6072 // Initially, assign the active gesture id to the active touch point
6073 // if there is one. No other touch id bits are mapped yet.
6074 if (!*outCancelPreviousGesture) {
6075 mappedTouchIdBits.markBit(activeTouchId);
6076 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6077 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6078 mPointerGesture.activeGestureId;
6079 } else {
6080 mPointerGesture.activeGestureId = -1;
6081 }
6082 } else {
6083 // Otherwise, assume we mapped all touches from the previous frame.
6084 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006085 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6086 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006087 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6088
6089 // Check whether we need to choose a new active gesture id because the
6090 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006091 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6092 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006093 !upTouchIdBits.isEmpty(); ) {
6094 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6095 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6096 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6097 mPointerGesture.activeGestureId = -1;
6098 break;
6099 }
6100 }
6101 }
6102
6103#if DEBUG_GESTURES
6104 ALOGD("Gestures: FREEFORM follow up "
6105 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6106 "activeGestureId=%d",
6107 mappedTouchIdBits.value, usedGestureIdBits.value,
6108 mPointerGesture.activeGestureId);
6109#endif
6110
Michael Wright842500e2015-03-13 17:32:02 -07006111 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006112 for (uint32_t i = 0; i < currentFingerCount; i++) {
6113 uint32_t touchId = idBits.clearFirstMarkedBit();
6114 uint32_t gestureId;
6115 if (!mappedTouchIdBits.hasBit(touchId)) {
6116 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6117 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6118#if DEBUG_GESTURES
6119 ALOGD("Gestures: FREEFORM "
6120 "new mapping for touch id %d -> gesture id %d",
6121 touchId, gestureId);
6122#endif
6123 } else {
6124 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6125#if DEBUG_GESTURES
6126 ALOGD("Gestures: FREEFORM "
6127 "existing mapping for touch id %d -> gesture id %d",
6128 touchId, gestureId);
6129#endif
6130 }
6131 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6132 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6133
6134 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006135 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006136 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6137 * mPointerXZoomScale;
6138 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6139 * mPointerYZoomScale;
6140 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6141
6142 mPointerGesture.currentGestureProperties[i].clear();
6143 mPointerGesture.currentGestureProperties[i].id = gestureId;
6144 mPointerGesture.currentGestureProperties[i].toolType =
6145 AMOTION_EVENT_TOOL_TYPE_FINGER;
6146 mPointerGesture.currentGestureCoords[i].clear();
6147 mPointerGesture.currentGestureCoords[i].setAxisValue(
6148 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6149 mPointerGesture.currentGestureCoords[i].setAxisValue(
6150 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6151 mPointerGesture.currentGestureCoords[i].setAxisValue(
6152 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6153 }
6154
6155 if (mPointerGesture.activeGestureId < 0) {
6156 mPointerGesture.activeGestureId =
6157 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6158#if DEBUG_GESTURES
6159 ALOGD("Gestures: FREEFORM new "
6160 "activeGestureId=%d", mPointerGesture.activeGestureId);
6161#endif
6162 }
6163 }
6164 }
6165
Michael Wright842500e2015-03-13 17:32:02 -07006166 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167
6168#if DEBUG_GESTURES
6169 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6170 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6171 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6172 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6173 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6174 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6175 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6176 uint32_t id = idBits.clearFirstMarkedBit();
6177 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6178 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6179 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6180 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6181 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6182 id, index, properties.toolType,
6183 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6184 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6185 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6186 }
6187 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6188 uint32_t id = idBits.clearFirstMarkedBit();
6189 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6190 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6191 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6192 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6193 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6194 id, index, properties.toolType,
6195 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6196 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6197 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6198 }
6199#endif
6200 return true;
6201}
6202
6203void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6204 mPointerSimple.currentCoords.clear();
6205 mPointerSimple.currentProperties.clear();
6206
6207 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006208 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6209 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6210 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6211 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6212 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006213 mPointerController->setPosition(x, y);
6214
Michael Wright842500e2015-03-13 17:32:02 -07006215 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006216 down = !hovering;
6217
6218 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006219 mPointerSimple.currentCoords.copyFrom(
6220 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006221 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6222 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6223 mPointerSimple.currentProperties.id = 0;
6224 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006225 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006226 } else {
6227 down = false;
6228 hovering = false;
6229 }
6230
6231 dispatchPointerSimple(when, policyFlags, down, hovering);
6232}
6233
6234void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6235 abortPointerSimple(when, policyFlags);
6236}
6237
6238void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6239 mPointerSimple.currentCoords.clear();
6240 mPointerSimple.currentProperties.clear();
6241
6242 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006243 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6244 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6245 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006246 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006247 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6248 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006249 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006250 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006251 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006252 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006253 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006254 * mPointerYMovementScale;
6255
6256 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6257 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6258
6259 mPointerController->move(deltaX, deltaY);
6260 } else {
6261 mPointerVelocityControl.reset();
6262 }
6263
Michael Wright842500e2015-03-13 17:32:02 -07006264 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006265 hovering = !down;
6266
6267 float x, y;
6268 mPointerController->getPosition(&x, &y);
6269 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006270 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006271 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6272 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6273 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6274 hovering ? 0.0f : 1.0f);
6275 mPointerSimple.currentProperties.id = 0;
6276 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006277 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 } else {
6279 mPointerVelocityControl.reset();
6280
6281 down = false;
6282 hovering = false;
6283 }
6284
6285 dispatchPointerSimple(when, policyFlags, down, hovering);
6286}
6287
6288void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6289 abortPointerSimple(when, policyFlags);
6290
6291 mPointerVelocityControl.reset();
6292}
6293
6294void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6295 bool down, bool hovering) {
6296 int32_t metaState = getContext()->getGlobalMetaState();
6297
Yi Kong9b14ac62018-07-17 13:48:38 -07006298 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006299 if (down || hovering) {
6300 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6301 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006302 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6304 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6305 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6306 }
6307 }
6308
6309 if (mPointerSimple.down && !down) {
6310 mPointerSimple.down = false;
6311
6312 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006313 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006314 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006315 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006316 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6317 mOrientedXPrecision, mOrientedYPrecision,
6318 mPointerSimple.downTime);
6319 getListener()->notifyMotion(&args);
6320 }
6321
6322 if (mPointerSimple.hovering && !hovering) {
6323 mPointerSimple.hovering = false;
6324
6325 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006326 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006327 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006328 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006329 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6330 mOrientedXPrecision, mOrientedYPrecision,
6331 mPointerSimple.downTime);
6332 getListener()->notifyMotion(&args);
6333 }
6334
6335 if (down) {
6336 if (!mPointerSimple.down) {
6337 mPointerSimple.down = true;
6338 mPointerSimple.downTime = when;
6339
6340 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006341 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006342 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006343 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006344 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6345 mOrientedXPrecision, mOrientedYPrecision,
6346 mPointerSimple.downTime);
6347 getListener()->notifyMotion(&args);
6348 }
6349
6350 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006351 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006352 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006353 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006354 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6355 mOrientedXPrecision, mOrientedYPrecision,
6356 mPointerSimple.downTime);
6357 getListener()->notifyMotion(&args);
6358 }
6359
6360 if (hovering) {
6361 if (!mPointerSimple.hovering) {
6362 mPointerSimple.hovering = true;
6363
6364 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006365 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006366 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006367 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006368 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006369 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6370 mOrientedXPrecision, mOrientedYPrecision,
6371 mPointerSimple.downTime);
6372 getListener()->notifyMotion(&args);
6373 }
6374
6375 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006376 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006377 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006378 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006379 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6381 mOrientedXPrecision, mOrientedYPrecision,
6382 mPointerSimple.downTime);
6383 getListener()->notifyMotion(&args);
6384 }
6385
Michael Wright842500e2015-03-13 17:32:02 -07006386 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6387 float vscroll = mCurrentRawState.rawVScroll;
6388 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006389 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6390 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006391
6392 // Send scroll.
6393 PointerCoords pointerCoords;
6394 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6395 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6396 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6397
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006398 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006399 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006400 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006401 1, &mPointerSimple.currentProperties, &pointerCoords,
6402 mOrientedXPrecision, mOrientedYPrecision,
6403 mPointerSimple.downTime);
6404 getListener()->notifyMotion(&args);
6405 }
6406
6407 // Save state.
6408 if (down || hovering) {
6409 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6410 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6411 } else {
6412 mPointerSimple.reset();
6413 }
6414}
6415
6416void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6417 mPointerSimple.currentCoords.clear();
6418 mPointerSimple.currentProperties.clear();
6419
6420 dispatchPointerSimple(when, policyFlags, false, false);
6421}
6422
6423void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006424 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006425 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006426 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006427 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6428 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006429 PointerCoords pointerCoords[MAX_POINTERS];
6430 PointerProperties pointerProperties[MAX_POINTERS];
6431 uint32_t pointerCount = 0;
6432 while (!idBits.isEmpty()) {
6433 uint32_t id = idBits.clearFirstMarkedBit();
6434 uint32_t index = idToIndex[id];
6435 pointerProperties[pointerCount].copyFrom(properties[index]);
6436 pointerCoords[pointerCount].copyFrom(coords[index]);
6437
6438 if (changedId >= 0 && id == uint32_t(changedId)) {
6439 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6440 }
6441
6442 pointerCount += 1;
6443 }
6444
6445 ALOG_ASSERT(pointerCount != 0);
6446
6447 if (changedId >= 0 && pointerCount == 1) {
6448 // Replace initial down and final up action.
6449 // We can compare the action without masking off the changed pointer index
6450 // because we know the index is 0.
6451 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6452 action = AMOTION_EVENT_ACTION_DOWN;
6453 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6454 action = AMOTION_EVENT_ACTION_UP;
6455 } else {
6456 // Can't happen.
6457 ALOG_ASSERT(false);
6458 }
6459 }
6460
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006461 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006462 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006463 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006464 xPrecision, yPrecision, downTime);
6465 getListener()->notifyMotion(&args);
6466}
6467
6468bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6469 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6470 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6471 BitSet32 idBits) const {
6472 bool changed = false;
6473 while (!idBits.isEmpty()) {
6474 uint32_t id = idBits.clearFirstMarkedBit();
6475 uint32_t inIndex = inIdToIndex[id];
6476 uint32_t outIndex = outIdToIndex[id];
6477
6478 const PointerProperties& curInProperties = inProperties[inIndex];
6479 const PointerCoords& curInCoords = inCoords[inIndex];
6480 PointerProperties& curOutProperties = outProperties[outIndex];
6481 PointerCoords& curOutCoords = outCoords[outIndex];
6482
6483 if (curInProperties != curOutProperties) {
6484 curOutProperties.copyFrom(curInProperties);
6485 changed = true;
6486 }
6487
6488 if (curInCoords != curOutCoords) {
6489 curOutCoords.copyFrom(curInCoords);
6490 changed = true;
6491 }
6492 }
6493 return changed;
6494}
6495
6496void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006497 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006498 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6499 }
6500}
6501
Jeff Brownc9aa6282015-02-11 19:03:28 -08006502void TouchInputMapper::cancelTouch(nsecs_t when) {
6503 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006504 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006505}
6506
Michael Wrightd02c5b62014-02-10 15:10:22 -08006507bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006508 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006509 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006510 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006511 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6512 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6513 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006514}
6515
6516const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6517 int32_t x, int32_t y) {
6518 size_t numVirtualKeys = mVirtualKeys.size();
6519 for (size_t i = 0; i < numVirtualKeys; i++) {
6520 const VirtualKey& virtualKey = mVirtualKeys[i];
6521
6522#if DEBUG_VIRTUAL_KEYS
6523 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6524 "left=%d, top=%d, right=%d, bottom=%d",
6525 x, y,
6526 virtualKey.keyCode, virtualKey.scanCode,
6527 virtualKey.hitLeft, virtualKey.hitTop,
6528 virtualKey.hitRight, virtualKey.hitBottom);
6529#endif
6530
6531 if (virtualKey.isHit(x, y)) {
6532 return & virtualKey;
6533 }
6534 }
6535
Yi Kong9b14ac62018-07-17 13:48:38 -07006536 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006537}
6538
Michael Wright842500e2015-03-13 17:32:02 -07006539void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6540 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6541 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006542
Michael Wright842500e2015-03-13 17:32:02 -07006543 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006544
6545 if (currentPointerCount == 0) {
6546 // No pointers to assign.
6547 return;
6548 }
6549
6550 if (lastPointerCount == 0) {
6551 // All pointers are new.
6552 for (uint32_t i = 0; i < currentPointerCount; i++) {
6553 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006554 current->rawPointerData.pointers[i].id = id;
6555 current->rawPointerData.idToIndex[id] = i;
6556 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006557 }
6558 return;
6559 }
6560
6561 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006562 && current->rawPointerData.pointers[0].toolType
6563 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006564 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006565 uint32_t id = last->rawPointerData.pointers[0].id;
6566 current->rawPointerData.pointers[0].id = id;
6567 current->rawPointerData.idToIndex[id] = 0;
6568 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006569 return;
6570 }
6571
6572 // General case.
6573 // We build a heap of squared euclidean distances between current and last pointers
6574 // associated with the current and last pointer indices. Then, we find the best
6575 // match (by distance) for each current pointer.
6576 // The pointers must have the same tool type but it is possible for them to
6577 // transition from hovering to touching or vice-versa while retaining the same id.
6578 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6579
6580 uint32_t heapSize = 0;
6581 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6582 currentPointerIndex++) {
6583 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6584 lastPointerIndex++) {
6585 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006586 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006587 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006588 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006589 if (currentPointer.toolType == lastPointer.toolType) {
6590 int64_t deltaX = currentPointer.x - lastPointer.x;
6591 int64_t deltaY = currentPointer.y - lastPointer.y;
6592
6593 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6594
6595 // Insert new element into the heap (sift up).
6596 heap[heapSize].currentPointerIndex = currentPointerIndex;
6597 heap[heapSize].lastPointerIndex = lastPointerIndex;
6598 heap[heapSize].distance = distance;
6599 heapSize += 1;
6600 }
6601 }
6602 }
6603
6604 // Heapify
6605 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6606 startIndex -= 1;
6607 for (uint32_t parentIndex = startIndex; ;) {
6608 uint32_t childIndex = parentIndex * 2 + 1;
6609 if (childIndex >= heapSize) {
6610 break;
6611 }
6612
6613 if (childIndex + 1 < heapSize
6614 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6615 childIndex += 1;
6616 }
6617
6618 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6619 break;
6620 }
6621
6622 swap(heap[parentIndex], heap[childIndex]);
6623 parentIndex = childIndex;
6624 }
6625 }
6626
6627#if DEBUG_POINTER_ASSIGNMENT
6628 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6629 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006630 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006631 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6632 heap[i].distance);
6633 }
6634#endif
6635
6636 // Pull matches out by increasing order of distance.
6637 // To avoid reassigning pointers that have already been matched, the loop keeps track
6638 // of which last and current pointers have been matched using the matchedXXXBits variables.
6639 // It also tracks the used pointer id bits.
6640 BitSet32 matchedLastBits(0);
6641 BitSet32 matchedCurrentBits(0);
6642 BitSet32 usedIdBits(0);
6643 bool first = true;
6644 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6645 while (heapSize > 0) {
6646 if (first) {
6647 // The first time through the loop, we just consume the root element of
6648 // the heap (the one with smallest distance).
6649 first = false;
6650 } else {
6651 // Previous iterations consumed the root element of the heap.
6652 // Pop root element off of the heap (sift down).
6653 heap[0] = heap[heapSize];
6654 for (uint32_t parentIndex = 0; ;) {
6655 uint32_t childIndex = parentIndex * 2 + 1;
6656 if (childIndex >= heapSize) {
6657 break;
6658 }
6659
6660 if (childIndex + 1 < heapSize
6661 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6662 childIndex += 1;
6663 }
6664
6665 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6666 break;
6667 }
6668
6669 swap(heap[parentIndex], heap[childIndex]);
6670 parentIndex = childIndex;
6671 }
6672
6673#if DEBUG_POINTER_ASSIGNMENT
6674 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6675 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006676 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006677 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6678 heap[i].distance);
6679 }
6680#endif
6681 }
6682
6683 heapSize -= 1;
6684
6685 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6686 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6687
6688 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6689 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6690
6691 matchedCurrentBits.markBit(currentPointerIndex);
6692 matchedLastBits.markBit(lastPointerIndex);
6693
Michael Wright842500e2015-03-13 17:32:02 -07006694 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6695 current->rawPointerData.pointers[currentPointerIndex].id = id;
6696 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6697 current->rawPointerData.markIdBit(id,
6698 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006699 usedIdBits.markBit(id);
6700
6701#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006702 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6703 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006704 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6705#endif
6706 break;
6707 }
6708 }
6709
6710 // Assign fresh ids to pointers that were not matched in the process.
6711 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6712 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6713 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6714
Michael Wright842500e2015-03-13 17:32:02 -07006715 current->rawPointerData.pointers[currentPointerIndex].id = id;
6716 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6717 current->rawPointerData.markIdBit(id,
6718 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006719
6720#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006721 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006722#endif
6723 }
6724}
6725
6726int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6727 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6728 return AKEY_STATE_VIRTUAL;
6729 }
6730
6731 size_t numVirtualKeys = mVirtualKeys.size();
6732 for (size_t i = 0; i < numVirtualKeys; i++) {
6733 const VirtualKey& virtualKey = mVirtualKeys[i];
6734 if (virtualKey.keyCode == keyCode) {
6735 return AKEY_STATE_UP;
6736 }
6737 }
6738
6739 return AKEY_STATE_UNKNOWN;
6740}
6741
6742int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6743 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6744 return AKEY_STATE_VIRTUAL;
6745 }
6746
6747 size_t numVirtualKeys = mVirtualKeys.size();
6748 for (size_t i = 0; i < numVirtualKeys; i++) {
6749 const VirtualKey& virtualKey = mVirtualKeys[i];
6750 if (virtualKey.scanCode == scanCode) {
6751 return AKEY_STATE_UP;
6752 }
6753 }
6754
6755 return AKEY_STATE_UNKNOWN;
6756}
6757
6758bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6759 const int32_t* keyCodes, uint8_t* outFlags) {
6760 size_t numVirtualKeys = mVirtualKeys.size();
6761 for (size_t i = 0; i < numVirtualKeys; i++) {
6762 const VirtualKey& virtualKey = mVirtualKeys[i];
6763
6764 for (size_t i = 0; i < numCodes; i++) {
6765 if (virtualKey.keyCode == keyCodes[i]) {
6766 outFlags[i] = 1;
6767 }
6768 }
6769 }
6770
6771 return true;
6772}
6773
6774
6775// --- SingleTouchInputMapper ---
6776
6777SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6778 TouchInputMapper(device) {
6779}
6780
6781SingleTouchInputMapper::~SingleTouchInputMapper() {
6782}
6783
6784void SingleTouchInputMapper::reset(nsecs_t when) {
6785 mSingleTouchMotionAccumulator.reset(getDevice());
6786
6787 TouchInputMapper::reset(when);
6788}
6789
6790void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6791 TouchInputMapper::process(rawEvent);
6792
6793 mSingleTouchMotionAccumulator.process(rawEvent);
6794}
6795
Michael Wright842500e2015-03-13 17:32:02 -07006796void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006797 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006798 outState->rawPointerData.pointerCount = 1;
6799 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006800
6801 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6802 && (mTouchButtonAccumulator.isHovering()
6803 || (mRawPointerAxes.pressure.valid
6804 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006805 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006806
Michael Wright842500e2015-03-13 17:32:02 -07006807 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006808 outPointer.id = 0;
6809 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6810 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6811 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6812 outPointer.touchMajor = 0;
6813 outPointer.touchMinor = 0;
6814 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6815 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6816 outPointer.orientation = 0;
6817 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6818 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6819 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6820 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6821 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6822 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6823 }
6824 outPointer.isHovering = isHovering;
6825 }
6826}
6827
6828void SingleTouchInputMapper::configureRawPointerAxes() {
6829 TouchInputMapper::configureRawPointerAxes();
6830
6831 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6832 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6833 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6834 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6835 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6836 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6837 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6838}
6839
6840bool SingleTouchInputMapper::hasStylus() const {
6841 return mTouchButtonAccumulator.hasStylus();
6842}
6843
6844
6845// --- MultiTouchInputMapper ---
6846
6847MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6848 TouchInputMapper(device) {
6849}
6850
6851MultiTouchInputMapper::~MultiTouchInputMapper() {
6852}
6853
6854void MultiTouchInputMapper::reset(nsecs_t when) {
6855 mMultiTouchMotionAccumulator.reset(getDevice());
6856
6857 mPointerIdBits.clear();
6858
6859 TouchInputMapper::reset(when);
6860}
6861
6862void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6863 TouchInputMapper::process(rawEvent);
6864
6865 mMultiTouchMotionAccumulator.process(rawEvent);
6866}
6867
Michael Wright842500e2015-03-13 17:32:02 -07006868void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006869 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6870 size_t outCount = 0;
6871 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006872 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006873
6874 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6875 const MultiTouchMotionAccumulator::Slot* inSlot =
6876 mMultiTouchMotionAccumulator.getSlot(inIndex);
6877 if (!inSlot->isInUse()) {
6878 continue;
6879 }
6880
6881 if (outCount >= MAX_POINTERS) {
6882#if DEBUG_POINTERS
6883 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6884 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006885 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006886#endif
6887 break; // too many fingers!
6888 }
6889
Michael Wright842500e2015-03-13 17:32:02 -07006890 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006891 outPointer.x = inSlot->getX();
6892 outPointer.y = inSlot->getY();
6893 outPointer.pressure = inSlot->getPressure();
6894 outPointer.touchMajor = inSlot->getTouchMajor();
6895 outPointer.touchMinor = inSlot->getTouchMinor();
6896 outPointer.toolMajor = inSlot->getToolMajor();
6897 outPointer.toolMinor = inSlot->getToolMinor();
6898 outPointer.orientation = inSlot->getOrientation();
6899 outPointer.distance = inSlot->getDistance();
6900 outPointer.tiltX = 0;
6901 outPointer.tiltY = 0;
6902
6903 outPointer.toolType = inSlot->getToolType();
6904 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6905 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6906 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6907 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6908 }
6909 }
6910
6911 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6912 && (mTouchButtonAccumulator.isHovering()
6913 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6914 outPointer.isHovering = isHovering;
6915
6916 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006917 if (mHavePointerIds) {
6918 int32_t trackingId = inSlot->getTrackingId();
6919 int32_t id = -1;
6920 if (trackingId >= 0) {
6921 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6922 uint32_t n = idBits.clearFirstMarkedBit();
6923 if (mPointerTrackingIdMap[n] == trackingId) {
6924 id = n;
6925 }
6926 }
6927
6928 if (id < 0 && !mPointerIdBits.isFull()) {
6929 id = mPointerIdBits.markFirstUnmarkedBit();
6930 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006931 }
Michael Wright842500e2015-03-13 17:32:02 -07006932 }
gaoshang1a632de2016-08-24 10:23:50 +08006933 if (id < 0) {
6934 mHavePointerIds = false;
6935 outState->rawPointerData.clearIdBits();
6936 newPointerIdBits.clear();
6937 } else {
6938 outPointer.id = id;
6939 outState->rawPointerData.idToIndex[id] = outCount;
6940 outState->rawPointerData.markIdBit(id, isHovering);
6941 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006942 }
Michael Wright842500e2015-03-13 17:32:02 -07006943 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006944 outCount += 1;
6945 }
6946
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006947 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006948 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006949 mPointerIdBits = newPointerIdBits;
6950
6951 mMultiTouchMotionAccumulator.finishSync();
6952}
6953
6954void MultiTouchInputMapper::configureRawPointerAxes() {
6955 TouchInputMapper::configureRawPointerAxes();
6956
6957 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6958 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6959 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6960 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6961 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6962 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6963 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6964 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6965 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6966 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6967 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6968
6969 if (mRawPointerAxes.trackingId.valid
6970 && mRawPointerAxes.slot.valid
6971 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6972 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6973 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006974 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6975 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006976 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006977 slotCount = MAX_SLOTS;
6978 }
6979 mMultiTouchMotionAccumulator.configure(getDevice(),
6980 slotCount, true /*usingSlotsProtocol*/);
6981 } else {
6982 mMultiTouchMotionAccumulator.configure(getDevice(),
6983 MAX_POINTERS, false /*usingSlotsProtocol*/);
6984 }
6985}
6986
6987bool MultiTouchInputMapper::hasStylus() const {
6988 return mMultiTouchMotionAccumulator.hasStylus()
6989 || mTouchButtonAccumulator.hasStylus();
6990}
6991
Michael Wright842500e2015-03-13 17:32:02 -07006992// --- ExternalStylusInputMapper
6993
6994ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6995 InputMapper(device) {
6996
6997}
6998
6999uint32_t ExternalStylusInputMapper::getSources() {
7000 return AINPUT_SOURCE_STYLUS;
7001}
7002
7003void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7004 InputMapper::populateDeviceInfo(info);
7005 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
7006 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
7007}
7008
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007009void ExternalStylusInputMapper::dump(std::string& dump) {
7010 dump += INDENT2 "External Stylus Input Mapper:\n";
7011 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007012 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007013 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007014 dumpStylusState(dump, mStylusState);
7015}
7016
7017void ExternalStylusInputMapper::configure(nsecs_t when,
7018 const InputReaderConfiguration* config, uint32_t changes) {
7019 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7020 mTouchButtonAccumulator.configure(getDevice());
7021}
7022
7023void ExternalStylusInputMapper::reset(nsecs_t when) {
7024 InputDevice* device = getDevice();
7025 mSingleTouchMotionAccumulator.reset(device);
7026 mTouchButtonAccumulator.reset(device);
7027 InputMapper::reset(when);
7028}
7029
7030void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7031 mSingleTouchMotionAccumulator.process(rawEvent);
7032 mTouchButtonAccumulator.process(rawEvent);
7033
7034 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7035 sync(rawEvent->when);
7036 }
7037}
7038
7039void ExternalStylusInputMapper::sync(nsecs_t when) {
7040 mStylusState.clear();
7041
7042 mStylusState.when = when;
7043
Michael Wright45ccacf2015-04-21 19:01:58 +01007044 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7045 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7046 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7047 }
7048
Michael Wright842500e2015-03-13 17:32:02 -07007049 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7050 if (mRawPressureAxis.valid) {
7051 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7052 } else if (mTouchButtonAccumulator.isToolActive()) {
7053 mStylusState.pressure = 1.0f;
7054 } else {
7055 mStylusState.pressure = 0.0f;
7056 }
7057
7058 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007059
7060 mContext->dispatchExternalStylusState(mStylusState);
7061}
7062
Michael Wrightd02c5b62014-02-10 15:10:22 -08007063
7064// --- JoystickInputMapper ---
7065
7066JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7067 InputMapper(device) {
7068}
7069
7070JoystickInputMapper::~JoystickInputMapper() {
7071}
7072
7073uint32_t JoystickInputMapper::getSources() {
7074 return AINPUT_SOURCE_JOYSTICK;
7075}
7076
7077void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7078 InputMapper::populateDeviceInfo(info);
7079
7080 for (size_t i = 0; i < mAxes.size(); i++) {
7081 const Axis& axis = mAxes.valueAt(i);
7082 addMotionRange(axis.axisInfo.axis, axis, info);
7083
7084 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7085 addMotionRange(axis.axisInfo.highAxis, axis, info);
7086
7087 }
7088 }
7089}
7090
7091void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7092 InputDeviceInfo* info) {
7093 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7094 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7095 /* In order to ease the transition for developers from using the old axes
7096 * to the newer, more semantically correct axes, we'll continue to register
7097 * the old axes as duplicates of their corresponding new ones. */
7098 int32_t compatAxis = getCompatAxis(axisId);
7099 if (compatAxis >= 0) {
7100 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7101 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7102 }
7103}
7104
7105/* A mapping from axes the joystick actually has to the axes that should be
7106 * artificially created for compatibility purposes.
7107 * Returns -1 if no compatibility axis is needed. */
7108int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7109 switch(axis) {
7110 case AMOTION_EVENT_AXIS_LTRIGGER:
7111 return AMOTION_EVENT_AXIS_BRAKE;
7112 case AMOTION_EVENT_AXIS_RTRIGGER:
7113 return AMOTION_EVENT_AXIS_GAS;
7114 }
7115 return -1;
7116}
7117
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007118void JoystickInputMapper::dump(std::string& dump) {
7119 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007120
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007121 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007122 size_t numAxes = mAxes.size();
7123 for (size_t i = 0; i < numAxes; i++) {
7124 const Axis& axis = mAxes.valueAt(i);
7125 const char* label = getAxisLabel(axis.axisInfo.axis);
7126 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007127 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007128 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007129 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007130 }
7131 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7132 label = getAxisLabel(axis.axisInfo.highAxis);
7133 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007134 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007135 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007136 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007137 axis.axisInfo.splitValue);
7138 }
7139 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007140 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007141 }
7142
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007143 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 -08007144 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007145 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007146 "highScale=%0.5f, highOffset=%0.5f\n",
7147 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007148 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007149 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7150 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7151 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7152 }
7153}
7154
7155void JoystickInputMapper::configure(nsecs_t when,
7156 const InputReaderConfiguration* config, uint32_t changes) {
7157 InputMapper::configure(when, config, changes);
7158
7159 if (!changes) { // first time only
7160 // Collect all axes.
7161 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7162 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7163 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7164 continue; // axis must be claimed by a different device
7165 }
7166
7167 RawAbsoluteAxisInfo rawAxisInfo;
7168 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7169 if (rawAxisInfo.valid) {
7170 // Map axis.
7171 AxisInfo axisInfo;
7172 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7173 if (!explicitlyMapped) {
7174 // Axis is not explicitly mapped, will choose a generic axis later.
7175 axisInfo.mode = AxisInfo::MODE_NORMAL;
7176 axisInfo.axis = -1;
7177 }
7178
7179 // Apply flat override.
7180 int32_t rawFlat = axisInfo.flatOverride < 0
7181 ? rawAxisInfo.flat : axisInfo.flatOverride;
7182
7183 // Calculate scaling factors and limits.
7184 Axis axis;
7185 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7186 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7187 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7188 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7189 scale, 0.0f, highScale, 0.0f,
7190 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7191 rawAxisInfo.resolution * scale);
7192 } else if (isCenteredAxis(axisInfo.axis)) {
7193 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7194 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7195 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7196 scale, offset, scale, offset,
7197 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7198 rawAxisInfo.resolution * scale);
7199 } else {
7200 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7201 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7202 scale, 0.0f, scale, 0.0f,
7203 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7204 rawAxisInfo.resolution * scale);
7205 }
7206
7207 // To eliminate noise while the joystick is at rest, filter out small variations
7208 // in axis values up front.
7209 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7210
7211 mAxes.add(abs, axis);
7212 }
7213 }
7214
7215 // If there are too many axes, start dropping them.
7216 // Prefer to keep explicitly mapped axes.
7217 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007218 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007219 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007220 pruneAxes(true);
7221 pruneAxes(false);
7222 }
7223
7224 // Assign generic axis ids to remaining axes.
7225 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7226 size_t numAxes = mAxes.size();
7227 for (size_t i = 0; i < numAxes; i++) {
7228 Axis& axis = mAxes.editValueAt(i);
7229 if (axis.axisInfo.axis < 0) {
7230 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7231 && haveAxis(nextGenericAxisId)) {
7232 nextGenericAxisId += 1;
7233 }
7234
7235 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7236 axis.axisInfo.axis = nextGenericAxisId;
7237 nextGenericAxisId += 1;
7238 } else {
7239 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7240 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007241 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007242 mAxes.removeItemsAt(i--);
7243 numAxes -= 1;
7244 }
7245 }
7246 }
7247 }
7248}
7249
7250bool JoystickInputMapper::haveAxis(int32_t axisId) {
7251 size_t numAxes = mAxes.size();
7252 for (size_t i = 0; i < numAxes; i++) {
7253 const Axis& axis = mAxes.valueAt(i);
7254 if (axis.axisInfo.axis == axisId
7255 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7256 && axis.axisInfo.highAxis == axisId)) {
7257 return true;
7258 }
7259 }
7260 return false;
7261}
7262
7263void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7264 size_t i = mAxes.size();
7265 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7266 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7267 continue;
7268 }
7269 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007270 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007271 mAxes.removeItemsAt(i);
7272 }
7273}
7274
7275bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7276 switch (axis) {
7277 case AMOTION_EVENT_AXIS_X:
7278 case AMOTION_EVENT_AXIS_Y:
7279 case AMOTION_EVENT_AXIS_Z:
7280 case AMOTION_EVENT_AXIS_RX:
7281 case AMOTION_EVENT_AXIS_RY:
7282 case AMOTION_EVENT_AXIS_RZ:
7283 case AMOTION_EVENT_AXIS_HAT_X:
7284 case AMOTION_EVENT_AXIS_HAT_Y:
7285 case AMOTION_EVENT_AXIS_ORIENTATION:
7286 case AMOTION_EVENT_AXIS_RUDDER:
7287 case AMOTION_EVENT_AXIS_WHEEL:
7288 return true;
7289 default:
7290 return false;
7291 }
7292}
7293
7294void JoystickInputMapper::reset(nsecs_t when) {
7295 // Recenter all axes.
7296 size_t numAxes = mAxes.size();
7297 for (size_t i = 0; i < numAxes; i++) {
7298 Axis& axis = mAxes.editValueAt(i);
7299 axis.resetValue();
7300 }
7301
7302 InputMapper::reset(when);
7303}
7304
7305void JoystickInputMapper::process(const RawEvent* rawEvent) {
7306 switch (rawEvent->type) {
7307 case EV_ABS: {
7308 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7309 if (index >= 0) {
7310 Axis& axis = mAxes.editValueAt(index);
7311 float newValue, highNewValue;
7312 switch (axis.axisInfo.mode) {
7313 case AxisInfo::MODE_INVERT:
7314 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7315 * axis.scale + axis.offset;
7316 highNewValue = 0.0f;
7317 break;
7318 case AxisInfo::MODE_SPLIT:
7319 if (rawEvent->value < axis.axisInfo.splitValue) {
7320 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7321 * axis.scale + axis.offset;
7322 highNewValue = 0.0f;
7323 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7324 newValue = 0.0f;
7325 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7326 * axis.highScale + axis.highOffset;
7327 } else {
7328 newValue = 0.0f;
7329 highNewValue = 0.0f;
7330 }
7331 break;
7332 default:
7333 newValue = rawEvent->value * axis.scale + axis.offset;
7334 highNewValue = 0.0f;
7335 break;
7336 }
7337 axis.newValue = newValue;
7338 axis.highNewValue = highNewValue;
7339 }
7340 break;
7341 }
7342
7343 case EV_SYN:
7344 switch (rawEvent->code) {
7345 case SYN_REPORT:
7346 sync(rawEvent->when, false /*force*/);
7347 break;
7348 }
7349 break;
7350 }
7351}
7352
7353void JoystickInputMapper::sync(nsecs_t when, bool force) {
7354 if (!filterAxes(force)) {
7355 return;
7356 }
7357
7358 int32_t metaState = mContext->getGlobalMetaState();
7359 int32_t buttonState = 0;
7360
7361 PointerProperties pointerProperties;
7362 pointerProperties.clear();
7363 pointerProperties.id = 0;
7364 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7365
7366 PointerCoords pointerCoords;
7367 pointerCoords.clear();
7368
7369 size_t numAxes = mAxes.size();
7370 for (size_t i = 0; i < numAxes; i++) {
7371 const Axis& axis = mAxes.valueAt(i);
7372 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7373 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7374 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7375 axis.highCurrentValue);
7376 }
7377 }
7378
7379 // Moving a joystick axis should not wake the device because joysticks can
7380 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7381 // button will likely wake the device.
7382 // TODO: Use the input device configuration to control this behavior more finely.
7383 uint32_t policyFlags = 0;
7384
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007385 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7386 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007387 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007388 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007389 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007390 getListener()->notifyMotion(&args);
7391}
7392
7393void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7394 int32_t axis, float value) {
7395 pointerCoords->setAxisValue(axis, value);
7396 /* In order to ease the transition for developers from using the old axes
7397 * to the newer, more semantically correct axes, we'll continue to produce
7398 * values for the old axes as mirrors of the value of their corresponding
7399 * new axes. */
7400 int32_t compatAxis = getCompatAxis(axis);
7401 if (compatAxis >= 0) {
7402 pointerCoords->setAxisValue(compatAxis, value);
7403 }
7404}
7405
7406bool JoystickInputMapper::filterAxes(bool force) {
7407 bool atLeastOneSignificantChange = force;
7408 size_t numAxes = mAxes.size();
7409 for (size_t i = 0; i < numAxes; i++) {
7410 Axis& axis = mAxes.editValueAt(i);
7411 if (force || hasValueChangedSignificantly(axis.filter,
7412 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7413 axis.currentValue = axis.newValue;
7414 atLeastOneSignificantChange = true;
7415 }
7416 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7417 if (force || hasValueChangedSignificantly(axis.filter,
7418 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7419 axis.highCurrentValue = axis.highNewValue;
7420 atLeastOneSignificantChange = true;
7421 }
7422 }
7423 }
7424 return atLeastOneSignificantChange;
7425}
7426
7427bool JoystickInputMapper::hasValueChangedSignificantly(
7428 float filter, float newValue, float currentValue, float min, float max) {
7429 if (newValue != currentValue) {
7430 // Filter out small changes in value unless the value is converging on the axis
7431 // bounds or center point. This is intended to reduce the amount of information
7432 // sent to applications by particularly noisy joysticks (such as PS3).
7433 if (fabs(newValue - currentValue) > filter
7434 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7435 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7436 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7437 return true;
7438 }
7439 }
7440 return false;
7441}
7442
7443bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7444 float filter, float newValue, float currentValue, float thresholdValue) {
7445 float newDistance = fabs(newValue - thresholdValue);
7446 if (newDistance < filter) {
7447 float oldDistance = fabs(currentValue - thresholdValue);
7448 if (newDistance < oldDistance) {
7449 return true;
7450 }
7451 }
7452 return false;
7453}
7454
7455} // namespace android