blob: 9dd14dc799ccec2890f793f10e3b68563bff8c4d [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));
994 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
995 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
996 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800997
998 const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
999 if (!ranges.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001000 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001001 for (size_t i = 0; i < ranges.size(); i++) {
1002 const InputDeviceInfo::MotionRange& range = ranges.itemAt(i);
1003 const char* label = getAxisLabel(range.axis);
1004 char name[32];
1005 if (label) {
1006 strncpy(name, label, sizeof(name));
1007 name[sizeof(name) - 1] = '\0';
1008 } else {
1009 snprintf(name, sizeof(name), "%d", range.axis);
1010 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001011 dump += StringPrintf(INDENT3 "%s: source=0x%08x, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08001012 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1013 name, range.source, range.min, range.max, range.flat, range.fuzz,
1014 range.resolution);
1015 }
1016 }
1017
1018 size_t numMappers = mMappers.size();
1019 for (size_t i = 0; i < numMappers; i++) {
1020 InputMapper* mapper = mMappers[i];
1021 mapper->dump(dump);
1022 }
1023}
1024
1025void InputDevice::addMapper(InputMapper* mapper) {
1026 mMappers.add(mapper);
1027}
1028
1029void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) {
1030 mSources = 0;
1031
1032 if (!isIgnored()) {
1033 if (!changes) { // first time only
1034 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1035 }
1036
1037 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1038 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1039 sp<KeyCharacterMap> keyboardLayout =
1040 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1041 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1042 bumpGeneration();
1043 }
1044 }
1045 }
1046
1047 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1048 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001049 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001050 if (mAlias != alias) {
1051 mAlias = alias;
1052 bumpGeneration();
1053 }
1054 }
1055 }
1056
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001057 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
1058 ssize_t index = config->disabledDevices.indexOf(mId);
1059 bool enabled = index < 0;
1060 setEnabled(enabled, when);
1061 }
1062
Michael Wrightd02c5b62014-02-10 15:10:22 -08001063 size_t numMappers = mMappers.size();
1064 for (size_t i = 0; i < numMappers; i++) {
1065 InputMapper* mapper = mMappers[i];
1066 mapper->configure(when, config, changes);
1067 mSources |= mapper->getSources();
1068 }
1069 }
1070}
1071
1072void InputDevice::reset(nsecs_t when) {
1073 size_t numMappers = mMappers.size();
1074 for (size_t i = 0; i < numMappers; i++) {
1075 InputMapper* mapper = mMappers[i];
1076 mapper->reset(when);
1077 }
1078
1079 mContext->updateGlobalMetaState();
1080
1081 notifyReset(when);
1082}
1083
1084void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1085 // Process all of the events in order for each mapper.
1086 // We cannot simply ask each mapper to process them in bulk because mappers may
1087 // have side-effects that must be interleaved. For example, joystick movement events and
1088 // gamepad button presses are handled by different mappers but they should be dispatched
1089 // in the order received.
1090 size_t numMappers = mMappers.size();
Ivan Lozano96f12992017-11-09 14:45:38 -08001091 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001092#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001093 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001094 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,
1095 rawEvent->when);
1096#endif
1097
1098 if (mDropUntilNextSync) {
1099 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1100 mDropUntilNextSync = false;
1101#if DEBUG_RAW_EVENTS
1102 ALOGD("Recovered from input event buffer overrun.");
1103#endif
1104 } else {
1105#if DEBUG_RAW_EVENTS
1106 ALOGD("Dropped input event while waiting for next input sync.");
1107#endif
1108 }
1109 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001110 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001111 mDropUntilNextSync = true;
1112 reset(rawEvent->when);
1113 } else {
1114 for (size_t i = 0; i < numMappers; i++) {
1115 InputMapper* mapper = mMappers[i];
1116 mapper->process(rawEvent);
1117 }
1118 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001119 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001120 }
1121}
1122
1123void InputDevice::timeoutExpired(nsecs_t when) {
1124 size_t numMappers = mMappers.size();
1125 for (size_t i = 0; i < numMappers; i++) {
1126 InputMapper* mapper = mMappers[i];
1127 mapper->timeoutExpired(when);
1128 }
1129}
1130
Michael Wright842500e2015-03-13 17:32:02 -07001131void InputDevice::updateExternalStylusState(const StylusState& state) {
1132 size_t numMappers = mMappers.size();
1133 for (size_t i = 0; i < numMappers; i++) {
1134 InputMapper* mapper = mMappers[i];
1135 mapper->updateExternalStylusState(state);
1136 }
1137}
1138
Michael Wrightd02c5b62014-02-10 15:10:22 -08001139void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
1140 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias,
Tim Kilbourn063ff532015-04-08 10:26:18 -07001141 mIsExternal, mHasMic);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001142 size_t numMappers = mMappers.size();
1143 for (size_t i = 0; i < numMappers; i++) {
1144 InputMapper* mapper = mMappers[i];
1145 mapper->populateDeviceInfo(outDeviceInfo);
1146 }
1147}
1148
1149int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1150 return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState);
1151}
1152
1153int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1154 return getState(sourceMask, scanCode, & InputMapper::getScanCodeState);
1155}
1156
1157int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1158 return getState(sourceMask, switchCode, & InputMapper::getSwitchState);
1159}
1160
1161int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1162 int32_t result = AKEY_STATE_UNKNOWN;
1163 size_t numMappers = mMappers.size();
1164 for (size_t i = 0; i < numMappers; i++) {
1165 InputMapper* mapper = mMappers[i];
1166 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1167 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1168 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1169 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1170 if (currentResult >= AKEY_STATE_DOWN) {
1171 return currentResult;
1172 } else if (currentResult == AKEY_STATE_UP) {
1173 result = currentResult;
1174 }
1175 }
1176 }
1177 return result;
1178}
1179
1180bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1181 const int32_t* keyCodes, uint8_t* outFlags) {
1182 bool result = false;
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 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1188 }
1189 }
1190 return result;
1191}
1192
1193void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1194 int32_t token) {
1195 size_t numMappers = mMappers.size();
1196 for (size_t i = 0; i < numMappers; i++) {
1197 InputMapper* mapper = mMappers[i];
1198 mapper->vibrate(pattern, patternSize, repeat, token);
1199 }
1200}
1201
1202void InputDevice::cancelVibrate(int32_t token) {
1203 size_t numMappers = mMappers.size();
1204 for (size_t i = 0; i < numMappers; i++) {
1205 InputMapper* mapper = mMappers[i];
1206 mapper->cancelVibrate(token);
1207 }
1208}
1209
Jeff Brownc9aa6282015-02-11 19:03:28 -08001210void InputDevice::cancelTouch(nsecs_t when) {
1211 size_t numMappers = mMappers.size();
1212 for (size_t i = 0; i < numMappers; i++) {
1213 InputMapper* mapper = mMappers[i];
1214 mapper->cancelTouch(when);
1215 }
1216}
1217
Michael Wrightd02c5b62014-02-10 15:10:22 -08001218int32_t InputDevice::getMetaState() {
1219 int32_t result = 0;
1220 size_t numMappers = mMappers.size();
1221 for (size_t i = 0; i < numMappers; i++) {
1222 InputMapper* mapper = mMappers[i];
1223 result |= mapper->getMetaState();
1224 }
1225 return result;
1226}
1227
Andrii Kulian763a3a42016-03-08 10:46:16 -08001228void InputDevice::updateMetaState(int32_t keyCode) {
1229 size_t numMappers = mMappers.size();
1230 for (size_t i = 0; i < numMappers; i++) {
1231 mMappers[i]->updateMetaState(keyCode);
1232 }
1233}
1234
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235void InputDevice::fadePointer() {
1236 size_t numMappers = mMappers.size();
1237 for (size_t i = 0; i < numMappers; i++) {
1238 InputMapper* mapper = mMappers[i];
1239 mapper->fadePointer();
1240 }
1241}
1242
1243void InputDevice::bumpGeneration() {
1244 mGeneration = mContext->bumpGeneration();
1245}
1246
1247void InputDevice::notifyReset(nsecs_t when) {
1248 NotifyDeviceResetArgs args(when, mId);
1249 mContext->getListener()->notifyDeviceReset(&args);
1250}
1251
1252
1253// --- CursorButtonAccumulator ---
1254
1255CursorButtonAccumulator::CursorButtonAccumulator() {
1256 clearButtons();
1257}
1258
1259void CursorButtonAccumulator::reset(InputDevice* device) {
1260 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1261 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1262 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1263 mBtnBack = device->isKeyPressed(BTN_BACK);
1264 mBtnSide = device->isKeyPressed(BTN_SIDE);
1265 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1266 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1267 mBtnTask = device->isKeyPressed(BTN_TASK);
1268}
1269
1270void CursorButtonAccumulator::clearButtons() {
1271 mBtnLeft = 0;
1272 mBtnRight = 0;
1273 mBtnMiddle = 0;
1274 mBtnBack = 0;
1275 mBtnSide = 0;
1276 mBtnForward = 0;
1277 mBtnExtra = 0;
1278 mBtnTask = 0;
1279}
1280
1281void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1282 if (rawEvent->type == EV_KEY) {
1283 switch (rawEvent->code) {
1284 case BTN_LEFT:
1285 mBtnLeft = rawEvent->value;
1286 break;
1287 case BTN_RIGHT:
1288 mBtnRight = rawEvent->value;
1289 break;
1290 case BTN_MIDDLE:
1291 mBtnMiddle = rawEvent->value;
1292 break;
1293 case BTN_BACK:
1294 mBtnBack = rawEvent->value;
1295 break;
1296 case BTN_SIDE:
1297 mBtnSide = rawEvent->value;
1298 break;
1299 case BTN_FORWARD:
1300 mBtnForward = rawEvent->value;
1301 break;
1302 case BTN_EXTRA:
1303 mBtnExtra = rawEvent->value;
1304 break;
1305 case BTN_TASK:
1306 mBtnTask = rawEvent->value;
1307 break;
1308 }
1309 }
1310}
1311
1312uint32_t CursorButtonAccumulator::getButtonState() const {
1313 uint32_t result = 0;
1314 if (mBtnLeft) {
1315 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1316 }
1317 if (mBtnRight) {
1318 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1319 }
1320 if (mBtnMiddle) {
1321 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1322 }
1323 if (mBtnBack || mBtnSide) {
1324 result |= AMOTION_EVENT_BUTTON_BACK;
1325 }
1326 if (mBtnForward || mBtnExtra) {
1327 result |= AMOTION_EVENT_BUTTON_FORWARD;
1328 }
1329 return result;
1330}
1331
1332
1333// --- CursorMotionAccumulator ---
1334
1335CursorMotionAccumulator::CursorMotionAccumulator() {
1336 clearRelativeAxes();
1337}
1338
1339void CursorMotionAccumulator::reset(InputDevice* device) {
1340 clearRelativeAxes();
1341}
1342
1343void CursorMotionAccumulator::clearRelativeAxes() {
1344 mRelX = 0;
1345 mRelY = 0;
1346}
1347
1348void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1349 if (rawEvent->type == EV_REL) {
1350 switch (rawEvent->code) {
1351 case REL_X:
1352 mRelX = rawEvent->value;
1353 break;
1354 case REL_Y:
1355 mRelY = rawEvent->value;
1356 break;
1357 }
1358 }
1359}
1360
1361void CursorMotionAccumulator::finishSync() {
1362 clearRelativeAxes();
1363}
1364
1365
1366// --- CursorScrollAccumulator ---
1367
1368CursorScrollAccumulator::CursorScrollAccumulator() :
1369 mHaveRelWheel(false), mHaveRelHWheel(false) {
1370 clearRelativeAxes();
1371}
1372
1373void CursorScrollAccumulator::configure(InputDevice* device) {
1374 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1375 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1376}
1377
1378void CursorScrollAccumulator::reset(InputDevice* device) {
1379 clearRelativeAxes();
1380}
1381
1382void CursorScrollAccumulator::clearRelativeAxes() {
1383 mRelWheel = 0;
1384 mRelHWheel = 0;
1385}
1386
1387void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1388 if (rawEvent->type == EV_REL) {
1389 switch (rawEvent->code) {
1390 case REL_WHEEL:
1391 mRelWheel = rawEvent->value;
1392 break;
1393 case REL_HWHEEL:
1394 mRelHWheel = rawEvent->value;
1395 break;
1396 }
1397 }
1398}
1399
1400void CursorScrollAccumulator::finishSync() {
1401 clearRelativeAxes();
1402}
1403
1404
1405// --- TouchButtonAccumulator ---
1406
1407TouchButtonAccumulator::TouchButtonAccumulator() :
1408 mHaveBtnTouch(false), mHaveStylus(false) {
1409 clearButtons();
1410}
1411
1412void TouchButtonAccumulator::configure(InputDevice* device) {
1413 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
1414 mHaveStylus = device->hasKey(BTN_TOOL_PEN)
1415 || device->hasKey(BTN_TOOL_RUBBER)
1416 || device->hasKey(BTN_TOOL_BRUSH)
1417 || device->hasKey(BTN_TOOL_PENCIL)
1418 || device->hasKey(BTN_TOOL_AIRBRUSH);
1419}
1420
1421void TouchButtonAccumulator::reset(InputDevice* device) {
1422 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1423 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001424 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
1425 mBtnStylus2 =
1426 device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001427 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1428 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1429 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1430 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1431 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1432 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1433 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1434 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1435 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1436 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1437 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1438}
1439
1440void TouchButtonAccumulator::clearButtons() {
1441 mBtnTouch = 0;
1442 mBtnStylus = 0;
1443 mBtnStylus2 = 0;
1444 mBtnToolFinger = 0;
1445 mBtnToolPen = 0;
1446 mBtnToolRubber = 0;
1447 mBtnToolBrush = 0;
1448 mBtnToolPencil = 0;
1449 mBtnToolAirbrush = 0;
1450 mBtnToolMouse = 0;
1451 mBtnToolLens = 0;
1452 mBtnToolDoubleTap = 0;
1453 mBtnToolTripleTap = 0;
1454 mBtnToolQuadTap = 0;
1455}
1456
1457void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1458 if (rawEvent->type == EV_KEY) {
1459 switch (rawEvent->code) {
1460 case BTN_TOUCH:
1461 mBtnTouch = rawEvent->value;
1462 break;
1463 case BTN_STYLUS:
1464 mBtnStylus = rawEvent->value;
1465 break;
1466 case BTN_STYLUS2:
Michael Wright842500e2015-03-13 17:32:02 -07001467 case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Michael Wrightd02c5b62014-02-10 15:10:22 -08001468 mBtnStylus2 = rawEvent->value;
1469 break;
1470 case BTN_TOOL_FINGER:
1471 mBtnToolFinger = rawEvent->value;
1472 break;
1473 case BTN_TOOL_PEN:
1474 mBtnToolPen = rawEvent->value;
1475 break;
1476 case BTN_TOOL_RUBBER:
1477 mBtnToolRubber = rawEvent->value;
1478 break;
1479 case BTN_TOOL_BRUSH:
1480 mBtnToolBrush = rawEvent->value;
1481 break;
1482 case BTN_TOOL_PENCIL:
1483 mBtnToolPencil = rawEvent->value;
1484 break;
1485 case BTN_TOOL_AIRBRUSH:
1486 mBtnToolAirbrush = rawEvent->value;
1487 break;
1488 case BTN_TOOL_MOUSE:
1489 mBtnToolMouse = rawEvent->value;
1490 break;
1491 case BTN_TOOL_LENS:
1492 mBtnToolLens = rawEvent->value;
1493 break;
1494 case BTN_TOOL_DOUBLETAP:
1495 mBtnToolDoubleTap = rawEvent->value;
1496 break;
1497 case BTN_TOOL_TRIPLETAP:
1498 mBtnToolTripleTap = rawEvent->value;
1499 break;
1500 case BTN_TOOL_QUADTAP:
1501 mBtnToolQuadTap = rawEvent->value;
1502 break;
1503 }
1504 }
1505}
1506
1507uint32_t TouchButtonAccumulator::getButtonState() const {
1508 uint32_t result = 0;
1509 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001510 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001511 }
1512 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001513 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001514 }
1515 return result;
1516}
1517
1518int32_t TouchButtonAccumulator::getToolType() const {
1519 if (mBtnToolMouse || mBtnToolLens) {
1520 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1521 }
1522 if (mBtnToolRubber) {
1523 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1524 }
1525 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1526 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1527 }
1528 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1529 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1530 }
1531 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1532}
1533
1534bool TouchButtonAccumulator::isToolActive() const {
1535 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber
1536 || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush
1537 || mBtnToolMouse || mBtnToolLens
1538 || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
1539}
1540
1541bool TouchButtonAccumulator::isHovering() const {
1542 return mHaveBtnTouch && !mBtnTouch;
1543}
1544
1545bool TouchButtonAccumulator::hasStylus() const {
1546 return mHaveStylus;
1547}
1548
1549
1550// --- RawPointerAxes ---
1551
1552RawPointerAxes::RawPointerAxes() {
1553 clear();
1554}
1555
1556void RawPointerAxes::clear() {
1557 x.clear();
1558 y.clear();
1559 pressure.clear();
1560 touchMajor.clear();
1561 touchMinor.clear();
1562 toolMajor.clear();
1563 toolMinor.clear();
1564 orientation.clear();
1565 distance.clear();
1566 tiltX.clear();
1567 tiltY.clear();
1568 trackingId.clear();
1569 slot.clear();
1570}
1571
1572
1573// --- RawPointerData ---
1574
1575RawPointerData::RawPointerData() {
1576 clear();
1577}
1578
1579void RawPointerData::clear() {
1580 pointerCount = 0;
1581 clearIdBits();
1582}
1583
1584void RawPointerData::copyFrom(const RawPointerData& other) {
1585 pointerCount = other.pointerCount;
1586 hoveringIdBits = other.hoveringIdBits;
1587 touchingIdBits = other.touchingIdBits;
1588
1589 for (uint32_t i = 0; i < pointerCount; i++) {
1590 pointers[i] = other.pointers[i];
1591
1592 int id = pointers[i].id;
1593 idToIndex[id] = other.idToIndex[id];
1594 }
1595}
1596
1597void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1598 float x = 0, y = 0;
1599 uint32_t count = touchingIdBits.count();
1600 if (count) {
1601 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) {
1602 uint32_t id = idBits.clearFirstMarkedBit();
1603 const Pointer& pointer = pointerForId(id);
1604 x += pointer.x;
1605 y += pointer.y;
1606 }
1607 x /= count;
1608 y /= count;
1609 }
1610 *outX = x;
1611 *outY = y;
1612}
1613
1614
1615// --- CookedPointerData ---
1616
1617CookedPointerData::CookedPointerData() {
1618 clear();
1619}
1620
1621void CookedPointerData::clear() {
1622 pointerCount = 0;
1623 hoveringIdBits.clear();
1624 touchingIdBits.clear();
1625}
1626
1627void CookedPointerData::copyFrom(const CookedPointerData& other) {
1628 pointerCount = other.pointerCount;
1629 hoveringIdBits = other.hoveringIdBits;
1630 touchingIdBits = other.touchingIdBits;
1631
1632 for (uint32_t i = 0; i < pointerCount; i++) {
1633 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1634 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1635
1636 int id = pointerProperties[i].id;
1637 idToIndex[id] = other.idToIndex[id];
1638 }
1639}
1640
1641
1642// --- SingleTouchMotionAccumulator ---
1643
1644SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1645 clearAbsoluteAxes();
1646}
1647
1648void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1649 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1650 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1651 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1652 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1653 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1654 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1655 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1656}
1657
1658void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1659 mAbsX = 0;
1660 mAbsY = 0;
1661 mAbsPressure = 0;
1662 mAbsToolWidth = 0;
1663 mAbsDistance = 0;
1664 mAbsTiltX = 0;
1665 mAbsTiltY = 0;
1666}
1667
1668void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1669 if (rawEvent->type == EV_ABS) {
1670 switch (rawEvent->code) {
1671 case ABS_X:
1672 mAbsX = rawEvent->value;
1673 break;
1674 case ABS_Y:
1675 mAbsY = rawEvent->value;
1676 break;
1677 case ABS_PRESSURE:
1678 mAbsPressure = rawEvent->value;
1679 break;
1680 case ABS_TOOL_WIDTH:
1681 mAbsToolWidth = rawEvent->value;
1682 break;
1683 case ABS_DISTANCE:
1684 mAbsDistance = rawEvent->value;
1685 break;
1686 case ABS_TILT_X:
1687 mAbsTiltX = rawEvent->value;
1688 break;
1689 case ABS_TILT_Y:
1690 mAbsTiltY = rawEvent->value;
1691 break;
1692 }
1693 }
1694}
1695
1696
1697// --- MultiTouchMotionAccumulator ---
1698
1699MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() :
Yi Kong9b14ac62018-07-17 13:48:38 -07001700 mCurrentSlot(-1), mSlots(nullptr), mSlotCount(0), mUsingSlotsProtocol(false),
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001701 mHaveStylus(false), mDeviceTimestamp(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001702}
1703
1704MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1705 delete[] mSlots;
1706}
1707
1708void MultiTouchMotionAccumulator::configure(InputDevice* device,
1709 size_t slotCount, bool usingSlotsProtocol) {
1710 mSlotCount = slotCount;
1711 mUsingSlotsProtocol = usingSlotsProtocol;
1712 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1713
1714 delete[] mSlots;
1715 mSlots = new Slot[slotCount];
1716}
1717
1718void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1719 // Unfortunately there is no way to read the initial contents of the slots.
1720 // So when we reset the accumulator, we must assume they are all zeroes.
1721 if (mUsingSlotsProtocol) {
1722 // Query the driver for the current slot index and use it as the initial slot
1723 // before we start reading events from the device. It is possible that the
1724 // current slot index will not be the same as it was when the first event was
1725 // written into the evdev buffer, which means the input mapper could start
1726 // out of sync with the initial state of the events in the evdev buffer.
1727 // In the extremely unlikely case that this happens, the data from
1728 // two slots will be confused until the next ABS_MT_SLOT event is received.
1729 // This can cause the touch point to "jump", but at least there will be
1730 // no stuck touches.
1731 int32_t initialSlot;
1732 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(),
1733 ABS_MT_SLOT, &initialSlot);
1734 if (status) {
1735 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1736 initialSlot = -1;
1737 }
1738 clearSlots(initialSlot);
1739 } else {
1740 clearSlots(-1);
1741 }
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001742 mDeviceTimestamp = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001743}
1744
1745void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1746 if (mSlots) {
1747 for (size_t i = 0; i < mSlotCount; i++) {
1748 mSlots[i].clear();
1749 }
1750 }
1751 mCurrentSlot = initialSlot;
1752}
1753
1754void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1755 if (rawEvent->type == EV_ABS) {
1756 bool newSlot = false;
1757 if (mUsingSlotsProtocol) {
1758 if (rawEvent->code == ABS_MT_SLOT) {
1759 mCurrentSlot = rawEvent->value;
1760 newSlot = true;
1761 }
1762 } else if (mCurrentSlot < 0) {
1763 mCurrentSlot = 0;
1764 }
1765
1766 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1767#if DEBUG_POINTERS
1768 if (newSlot) {
1769 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001770 "should be between 0 and %zd; ignoring this slot.",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001771 mCurrentSlot, mSlotCount - 1);
1772 }
1773#endif
1774 } else {
1775 Slot* slot = &mSlots[mCurrentSlot];
1776
1777 switch (rawEvent->code) {
1778 case ABS_MT_POSITION_X:
1779 slot->mInUse = true;
1780 slot->mAbsMTPositionX = rawEvent->value;
1781 break;
1782 case ABS_MT_POSITION_Y:
1783 slot->mInUse = true;
1784 slot->mAbsMTPositionY = rawEvent->value;
1785 break;
1786 case ABS_MT_TOUCH_MAJOR:
1787 slot->mInUse = true;
1788 slot->mAbsMTTouchMajor = rawEvent->value;
1789 break;
1790 case ABS_MT_TOUCH_MINOR:
1791 slot->mInUse = true;
1792 slot->mAbsMTTouchMinor = rawEvent->value;
1793 slot->mHaveAbsMTTouchMinor = true;
1794 break;
1795 case ABS_MT_WIDTH_MAJOR:
1796 slot->mInUse = true;
1797 slot->mAbsMTWidthMajor = rawEvent->value;
1798 break;
1799 case ABS_MT_WIDTH_MINOR:
1800 slot->mInUse = true;
1801 slot->mAbsMTWidthMinor = rawEvent->value;
1802 slot->mHaveAbsMTWidthMinor = true;
1803 break;
1804 case ABS_MT_ORIENTATION:
1805 slot->mInUse = true;
1806 slot->mAbsMTOrientation = rawEvent->value;
1807 break;
1808 case ABS_MT_TRACKING_ID:
1809 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1810 // The slot is no longer in use but it retains its previous contents,
1811 // which may be reused for subsequent touches.
1812 slot->mInUse = false;
1813 } else {
1814 slot->mInUse = true;
1815 slot->mAbsMTTrackingId = rawEvent->value;
1816 }
1817 break;
1818 case ABS_MT_PRESSURE:
1819 slot->mInUse = true;
1820 slot->mAbsMTPressure = rawEvent->value;
1821 break;
1822 case ABS_MT_DISTANCE:
1823 slot->mInUse = true;
1824 slot->mAbsMTDistance = rawEvent->value;
1825 break;
1826 case ABS_MT_TOOL_TYPE:
1827 slot->mInUse = true;
1828 slot->mAbsMTToolType = rawEvent->value;
1829 slot->mHaveAbsMTToolType = true;
1830 break;
1831 }
1832 }
1833 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1834 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1835 mCurrentSlot += 1;
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08001836 } else if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
1837 mDeviceTimestamp = rawEvent->value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001838 }
1839}
1840
1841void MultiTouchMotionAccumulator::finishSync() {
1842 if (!mUsingSlotsProtocol) {
1843 clearSlots(-1);
1844 }
1845}
1846
1847bool MultiTouchMotionAccumulator::hasStylus() const {
1848 return mHaveStylus;
1849}
1850
1851
1852// --- MultiTouchMotionAccumulator::Slot ---
1853
1854MultiTouchMotionAccumulator::Slot::Slot() {
1855 clear();
1856}
1857
1858void MultiTouchMotionAccumulator::Slot::clear() {
1859 mInUse = false;
1860 mHaveAbsMTTouchMinor = false;
1861 mHaveAbsMTWidthMinor = false;
1862 mHaveAbsMTToolType = false;
1863 mAbsMTPositionX = 0;
1864 mAbsMTPositionY = 0;
1865 mAbsMTTouchMajor = 0;
1866 mAbsMTTouchMinor = 0;
1867 mAbsMTWidthMajor = 0;
1868 mAbsMTWidthMinor = 0;
1869 mAbsMTOrientation = 0;
1870 mAbsMTTrackingId = -1;
1871 mAbsMTPressure = 0;
1872 mAbsMTDistance = 0;
1873 mAbsMTToolType = 0;
1874}
1875
1876int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1877 if (mHaveAbsMTToolType) {
1878 switch (mAbsMTToolType) {
1879 case MT_TOOL_FINGER:
1880 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1881 case MT_TOOL_PEN:
1882 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1883 }
1884 }
1885 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1886}
1887
1888
1889// --- InputMapper ---
1890
1891InputMapper::InputMapper(InputDevice* device) :
1892 mDevice(device), mContext(device->getContext()) {
1893}
1894
1895InputMapper::~InputMapper() {
1896}
1897
1898void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1899 info->addSource(getSources());
1900}
1901
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001902void InputMapper::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001903}
1904
1905void InputMapper::configure(nsecs_t when,
1906 const InputReaderConfiguration* config, uint32_t changes) {
1907}
1908
1909void InputMapper::reset(nsecs_t when) {
1910}
1911
1912void InputMapper::timeoutExpired(nsecs_t when) {
1913}
1914
1915int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1916 return AKEY_STATE_UNKNOWN;
1917}
1918
1919int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1920 return AKEY_STATE_UNKNOWN;
1921}
1922
1923int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1924 return AKEY_STATE_UNKNOWN;
1925}
1926
1927bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
1928 const int32_t* keyCodes, uint8_t* outFlags) {
1929 return false;
1930}
1931
1932void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
1933 int32_t token) {
1934}
1935
1936void InputMapper::cancelVibrate(int32_t token) {
1937}
1938
Jeff Brownc9aa6282015-02-11 19:03:28 -08001939void InputMapper::cancelTouch(nsecs_t when) {
1940}
1941
Michael Wrightd02c5b62014-02-10 15:10:22 -08001942int32_t InputMapper::getMetaState() {
1943 return 0;
1944}
1945
Andrii Kulian763a3a42016-03-08 10:46:16 -08001946void InputMapper::updateMetaState(int32_t keyCode) {
1947}
1948
Michael Wright842500e2015-03-13 17:32:02 -07001949void InputMapper::updateExternalStylusState(const StylusState& state) {
1950
1951}
1952
Michael Wrightd02c5b62014-02-10 15:10:22 -08001953void InputMapper::fadePointer() {
1954}
1955
1956status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
1957 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
1958}
1959
1960void InputMapper::bumpGeneration() {
1961 mDevice->bumpGeneration();
1962}
1963
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001964void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump,
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965 const RawAbsoluteAxisInfo& axis, const char* name) {
1966 if (axis.valid) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001967 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968 name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
1969 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001970 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001971 }
1972}
1973
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001974void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
1975 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
1976 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
1977 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
1978 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07001979}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001980
1981// --- SwitchInputMapper ---
1982
1983SwitchInputMapper::SwitchInputMapper(InputDevice* device) :
Michael Wrightbcbf97e2014-08-29 14:31:32 -07001984 InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001985}
1986
1987SwitchInputMapper::~SwitchInputMapper() {
1988}
1989
1990uint32_t SwitchInputMapper::getSources() {
1991 return AINPUT_SOURCE_SWITCH;
1992}
1993
1994void SwitchInputMapper::process(const RawEvent* rawEvent) {
1995 switch (rawEvent->type) {
1996 case EV_SW:
1997 processSwitch(rawEvent->code, rawEvent->value);
1998 break;
1999
2000 case EV_SYN:
2001 if (rawEvent->code == SYN_REPORT) {
2002 sync(rawEvent->when);
2003 }
2004 }
2005}
2006
2007void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2008 if (switchCode >= 0 && switchCode < 32) {
2009 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002010 mSwitchValues |= 1 << switchCode;
2011 } else {
2012 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002013 }
2014 mUpdatedSwitchMask |= 1 << switchCode;
2015 }
2016}
2017
2018void SwitchInputMapper::sync(nsecs_t when) {
2019 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002020 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002021 NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 getListener()->notifySwitch(&args);
2023
Michael Wrightd02c5b62014-02-10 15:10:22 -08002024 mUpdatedSwitchMask = 0;
2025 }
2026}
2027
2028int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2029 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2030}
2031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002032void SwitchInputMapper::dump(std::string& dump) {
2033 dump += INDENT2 "Switch Input Mapper:\n";
2034 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002035}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
2037// --- VibratorInputMapper ---
2038
2039VibratorInputMapper::VibratorInputMapper(InputDevice* device) :
2040 InputMapper(device), mVibrating(false) {
2041}
2042
2043VibratorInputMapper::~VibratorInputMapper() {
2044}
2045
2046uint32_t VibratorInputMapper::getSources() {
2047 return 0;
2048}
2049
2050void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2051 InputMapper::populateDeviceInfo(info);
2052
2053 info->setVibrator(true);
2054}
2055
2056void VibratorInputMapper::process(const RawEvent* rawEvent) {
2057 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2058}
2059
2060void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
2061 int32_t token) {
2062#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002063 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002064 for (size_t i = 0; i < patternSize; i++) {
2065 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002066 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002067 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002068 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002069 }
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002070 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002071 getDeviceId(), patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072#endif
2073
2074 mVibrating = true;
2075 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2076 mPatternSize = patternSize;
2077 mRepeat = repeat;
2078 mToken = token;
2079 mIndex = -1;
2080
2081 nextStep();
2082}
2083
2084void VibratorInputMapper::cancelVibrate(int32_t token) {
2085#if DEBUG_VIBRATOR
2086 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2087#endif
2088
2089 if (mVibrating && mToken == token) {
2090 stopVibrating();
2091 }
2092}
2093
2094void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2095 if (mVibrating) {
2096 if (when >= mNextStepTime) {
2097 nextStep();
2098 } else {
2099 getContext()->requestTimeoutAtTime(mNextStepTime);
2100 }
2101 }
2102}
2103
2104void VibratorInputMapper::nextStep() {
2105 mIndex += 1;
2106 if (size_t(mIndex) >= mPatternSize) {
2107 if (mRepeat < 0) {
2108 // We are done.
2109 stopVibrating();
2110 return;
2111 }
2112 mIndex = mRepeat;
2113 }
2114
2115 bool vibratorOn = mIndex & 1;
2116 nsecs_t duration = mPattern[mIndex];
2117 if (vibratorOn) {
2118#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002119 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120#endif
2121 getEventHub()->vibrate(getDeviceId(), duration);
2122 } else {
2123#if DEBUG_VIBRATOR
2124 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2125#endif
2126 getEventHub()->cancelVibrate(getDeviceId());
2127 }
2128 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2129 mNextStepTime = now + duration;
2130 getContext()->requestTimeoutAtTime(mNextStepTime);
2131#if DEBUG_VIBRATOR
2132 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2133#endif
2134}
2135
2136void VibratorInputMapper::stopVibrating() {
2137 mVibrating = false;
2138#if DEBUG_VIBRATOR
2139 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2140#endif
2141 getEventHub()->cancelVibrate(getDeviceId());
2142}
2143
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002144void VibratorInputMapper::dump(std::string& dump) {
2145 dump += INDENT2 "Vibrator Input Mapper:\n";
2146 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002147}
2148
2149
2150// --- KeyboardInputMapper ---
2151
2152KeyboardInputMapper::KeyboardInputMapper(InputDevice* device,
2153 uint32_t source, int32_t keyboardType) :
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002154 InputMapper(device), mSource(source), mKeyboardType(keyboardType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002155}
2156
2157KeyboardInputMapper::~KeyboardInputMapper() {
2158}
2159
2160uint32_t KeyboardInputMapper::getSources() {
2161 return mSource;
2162}
2163
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002164int32_t KeyboardInputMapper::getOrientation() {
2165 if (mViewport) {
2166 return mViewport->orientation;
2167 }
2168 return DISPLAY_ORIENTATION_0;
2169}
2170
2171int32_t KeyboardInputMapper::getDisplayId() {
2172 if (mViewport) {
2173 return mViewport->displayId;
2174 }
2175 return ADISPLAY_ID_NONE;
2176}
2177
Michael Wrightd02c5b62014-02-10 15:10:22 -08002178void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2179 InputMapper::populateDeviceInfo(info);
2180
2181 info->setKeyboardType(mKeyboardType);
2182 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2183}
2184
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002185void KeyboardInputMapper::dump(std::string& dump) {
2186 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002187 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002188 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002189 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002190 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2191 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2192 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002193}
2194
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195void KeyboardInputMapper::configure(nsecs_t when,
2196 const InputReaderConfiguration* config, uint32_t changes) {
2197 InputMapper::configure(when, config, changes);
2198
2199 if (!changes) { // first time only
2200 // Configure basic parameters.
2201 configureParameters();
2202 }
2203
2204 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002205 if (mParameters.orientationAware) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002206 mViewport = config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002207 }
2208 }
2209}
2210
Ivan Podogovb9afef32017-02-13 15:34:32 +00002211static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const *property) {
2212 int32_t mapped = 0;
2213 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2214 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2215 if (stemKeyRotationMap[i][0] == keyCode) {
2216 stemKeyRotationMap[i][1] = mapped;
2217 return;
2218 }
2219 }
2220 }
2221}
2222
Michael Wrightd02c5b62014-02-10 15:10:22 -08002223void KeyboardInputMapper::configureParameters() {
2224 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002225 const PropertyMap& config = getDevice()->getConfiguration();
2226 config.tryGetProperty(String8("keyboard.orientationAware"),
Michael Wrightd02c5b62014-02-10 15:10:22 -08002227 mParameters.orientationAware);
2228
Michael Wrightd02c5b62014-02-10 15:10:22 -08002229 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002230 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2231 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2232 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2233 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002234 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002235
2236 mParameters.handlesKeyRepeat = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002237 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"),
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002238 mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002239}
2240
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002241void KeyboardInputMapper::dumpParameters(std::string& dump) {
2242 dump += INDENT3 "Parameters:\n";
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002243 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002244 toString(mParameters.orientationAware));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002245 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n",
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002246 toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002247}
2248
2249void KeyboardInputMapper::reset(nsecs_t when) {
2250 mMetaState = AMETA_NONE;
2251 mDownTime = 0;
2252 mKeyDowns.clear();
2253 mCurrentHidUsage = 0;
2254
2255 resetLedState();
2256
2257 InputMapper::reset(when);
2258}
2259
2260void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2261 switch (rawEvent->type) {
2262 case EV_KEY: {
2263 int32_t scanCode = rawEvent->code;
2264 int32_t usageCode = mCurrentHidUsage;
2265 mCurrentHidUsage = 0;
2266
2267 if (isKeyboardOrGamepadKey(scanCode)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002268 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002269 }
2270 break;
2271 }
2272 case EV_MSC: {
2273 if (rawEvent->code == MSC_SCAN) {
2274 mCurrentHidUsage = rawEvent->value;
2275 }
2276 break;
2277 }
2278 case EV_SYN: {
2279 if (rawEvent->code == SYN_REPORT) {
2280 mCurrentHidUsage = 0;
2281 }
2282 }
2283 }
2284}
2285
2286bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
2287 return scanCode < BTN_MOUSE
2288 || scanCode >= KEY_OK
2289 || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE)
2290 || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
2291}
2292
Michael Wright58ba9882017-07-26 16:19:11 +01002293bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2294 switch (keyCode) {
2295 case AKEYCODE_MEDIA_PLAY:
2296 case AKEYCODE_MEDIA_PAUSE:
2297 case AKEYCODE_MEDIA_PLAY_PAUSE:
2298 case AKEYCODE_MUTE:
2299 case AKEYCODE_HEADSETHOOK:
2300 case AKEYCODE_MEDIA_STOP:
2301 case AKEYCODE_MEDIA_NEXT:
2302 case AKEYCODE_MEDIA_PREVIOUS:
2303 case AKEYCODE_MEDIA_REWIND:
2304 case AKEYCODE_MEDIA_RECORD:
2305 case AKEYCODE_MEDIA_FAST_FORWARD:
2306 case AKEYCODE_MEDIA_SKIP_FORWARD:
2307 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2308 case AKEYCODE_MEDIA_STEP_FORWARD:
2309 case AKEYCODE_MEDIA_STEP_BACKWARD:
2310 case AKEYCODE_MEDIA_AUDIO_TRACK:
2311 case AKEYCODE_VOLUME_UP:
2312 case AKEYCODE_VOLUME_DOWN:
2313 case AKEYCODE_VOLUME_MUTE:
2314 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2315 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2316 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2317 return true;
2318 }
2319 return false;
2320}
2321
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002322void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode,
2323 int32_t usageCode) {
2324 int32_t keyCode;
2325 int32_t keyMetaState;
2326 uint32_t policyFlags;
2327
2328 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState,
2329 &keyCode, &keyMetaState, &policyFlags)) {
2330 keyCode = AKEYCODE_UNKNOWN;
2331 keyMetaState = mMetaState;
2332 policyFlags = 0;
2333 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002334
2335 if (down) {
2336 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002337 if (mParameters.orientationAware) {
2338 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002339 }
2340
2341 // Add key down.
2342 ssize_t keyDownIndex = findKeyDown(scanCode);
2343 if (keyDownIndex >= 0) {
2344 // key repeat, be sure to use same keycode as before in case of rotation
2345 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2346 } else {
2347 // key down
2348 if ((policyFlags & POLICY_FLAG_VIRTUAL)
2349 && mContext->shouldDropVirtualKey(when,
2350 getDevice(), keyCode, scanCode)) {
2351 return;
2352 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002353 if (policyFlags & POLICY_FLAG_GESTURE) {
2354 mDevice->cancelTouch(when);
2355 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002356
2357 mKeyDowns.push();
2358 KeyDown& keyDown = mKeyDowns.editTop();
2359 keyDown.keyCode = keyCode;
2360 keyDown.scanCode = scanCode;
2361 }
2362
2363 mDownTime = when;
2364 } else {
2365 // Remove key down.
2366 ssize_t keyDownIndex = findKeyDown(scanCode);
2367 if (keyDownIndex >= 0) {
2368 // key up, be sure to use same keycode as before in case of rotation
2369 keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;
2370 mKeyDowns.removeAt(size_t(keyDownIndex));
2371 } else {
2372 // key was not actually down
2373 ALOGI("Dropping key up from device %s because the key was not down. "
2374 "keyCode=%d, scanCode=%d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01002375 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002376 return;
2377 }
2378 }
2379
Andrii Kulian763a3a42016-03-08 10:46:16 -08002380 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002381 // If global meta state changed send it along with the key.
2382 // If it has not changed then we'll use what keymap gave us,
2383 // since key replacement logic might temporarily reset a few
2384 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002385 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386 }
2387
2388 nsecs_t downTime = mDownTime;
2389
2390 // Key down on external an keyboard should wake the device.
2391 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2392 // For internal keyboards, the key layout file should specify the policy flags for
2393 // each wake key individually.
2394 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002395 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002396 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002397 }
2398
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002399 if (mParameters.handlesKeyRepeat) {
2400 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2401 }
2402
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002403 NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002404 down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002405 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002406 getListener()->notifyKey(&args);
2407}
2408
2409ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2410 size_t n = mKeyDowns.size();
2411 for (size_t i = 0; i < n; i++) {
2412 if (mKeyDowns[i].scanCode == scanCode) {
2413 return i;
2414 }
2415 }
2416 return -1;
2417}
2418
2419int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2420 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2421}
2422
2423int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2424 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2425}
2426
2427bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
2428 const int32_t* keyCodes, uint8_t* outFlags) {
2429 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2430}
2431
2432int32_t KeyboardInputMapper::getMetaState() {
2433 return mMetaState;
2434}
2435
Andrii Kulian763a3a42016-03-08 10:46:16 -08002436void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2437 updateMetaStateIfNeeded(keyCode, false);
2438}
2439
2440bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2441 int32_t oldMetaState = mMetaState;
2442 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2443 bool metaStateChanged = oldMetaState != newMetaState;
2444 if (metaStateChanged) {
2445 mMetaState = newMetaState;
2446 updateLedState(false);
2447
2448 getContext()->updateGlobalMetaState();
2449 }
2450
2451 return metaStateChanged;
2452}
2453
Michael Wrightd02c5b62014-02-10 15:10:22 -08002454void KeyboardInputMapper::resetLedState() {
2455 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2456 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2457 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2458
2459 updateLedState(true);
2460}
2461
2462void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2463 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2464 ledState.on = false;
2465}
2466
2467void KeyboardInputMapper::updateLedState(bool reset) {
2468 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK,
2469 AMETA_CAPS_LOCK_ON, reset);
2470 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK,
2471 AMETA_NUM_LOCK_ON, reset);
2472 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK,
2473 AMETA_SCROLL_LOCK_ON, reset);
2474}
2475
2476void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState,
2477 int32_t led, int32_t modifier, bool reset) {
2478 if (ledState.avail) {
2479 bool desiredState = (mMetaState & modifier) != 0;
2480 if (reset || ledState.on != desiredState) {
2481 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2482 ledState.on = desiredState;
2483 }
2484 }
2485}
2486
2487
2488// --- CursorInputMapper ---
2489
2490CursorInputMapper::CursorInputMapper(InputDevice* device) :
2491 InputMapper(device) {
2492}
2493
2494CursorInputMapper::~CursorInputMapper() {
2495}
2496
2497uint32_t CursorInputMapper::getSources() {
2498 return mSource;
2499}
2500
2501void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2502 InputMapper::populateDeviceInfo(info);
2503
2504 if (mParameters.mode == Parameters::MODE_POINTER) {
2505 float minX, minY, maxX, maxY;
2506 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2507 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2508 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2509 }
2510 } else {
2511 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2512 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2513 }
2514 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2515
2516 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2517 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2518 }
2519 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2520 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2521 }
2522}
2523
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002524void CursorInputMapper::dump(std::string& dump) {
2525 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002527 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2528 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2529 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2530 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2531 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002532 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002533 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002534 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002535 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2536 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2537 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2538 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2539 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2540 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541}
2542
2543void CursorInputMapper::configure(nsecs_t when,
2544 const InputReaderConfiguration* config, uint32_t changes) {
2545 InputMapper::configure(when, config, changes);
2546
2547 if (!changes) { // first time only
2548 mCursorScrollAccumulator.configure(getDevice());
2549
2550 // Configure basic parameters.
2551 configureParameters();
2552
2553 // Configure device mode.
2554 switch (mParameters.mode) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002555 case Parameters::MODE_POINTER_RELATIVE:
2556 // Should not happen during first time configuration.
2557 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2558 mParameters.mode = Parameters::MODE_POINTER;
Chih-Hung Hsieh8d1b40a2018-10-19 11:38:06 -07002559 [[fallthrough]];
Michael Wrightd02c5b62014-02-10 15:10:22 -08002560 case Parameters::MODE_POINTER:
2561 mSource = AINPUT_SOURCE_MOUSE;
2562 mXPrecision = 1.0f;
2563 mYPrecision = 1.0f;
2564 mXScale = 1.0f;
2565 mYScale = 1.0f;
2566 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2567 break;
2568 case Parameters::MODE_NAVIGATION:
2569 mSource = AINPUT_SOURCE_TRACKBALL;
2570 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2571 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2572 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2573 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2574 break;
2575 }
2576
2577 mVWheelScale = 1.0f;
2578 mHWheelScale = 1.0f;
2579 }
2580
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002581 if ((!changes && config->pointerCapture)
2582 || (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
2583 if (config->pointerCapture) {
2584 if (mParameters.mode == Parameters::MODE_POINTER) {
2585 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2586 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2587 // Keep PointerController around in order to preserve the pointer position.
2588 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2589 } else {
2590 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2591 }
2592 } else {
2593 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2594 mParameters.mode = Parameters::MODE_POINTER;
2595 mSource = AINPUT_SOURCE_MOUSE;
2596 } else {
2597 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2598 }
2599 }
2600 bumpGeneration();
2601 if (changes) {
2602 getDevice()->notifyReset(when);
2603 }
2604 }
2605
Michael Wrightd02c5b62014-02-10 15:10:22 -08002606 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2607 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2608 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2609 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2610 }
2611
2612 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002613 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002614 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002615 std::optional<DisplayViewport> internalViewport =
2616 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "");
2617 if (internalViewport) {
2618 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002619 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002620 }
2621 bumpGeneration();
2622 }
2623}
2624
2625void CursorInputMapper::configureParameters() {
2626 mParameters.mode = Parameters::MODE_POINTER;
2627 String8 cursorModeString;
2628 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2629 if (cursorModeString == "navigation") {
2630 mParameters.mode = Parameters::MODE_NAVIGATION;
2631 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2632 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2633 }
2634 }
2635
2636 mParameters.orientationAware = false;
2637 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
2638 mParameters.orientationAware);
2639
2640 mParameters.hasAssociatedDisplay = false;
2641 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2642 mParameters.hasAssociatedDisplay = true;
2643 }
2644}
2645
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002646void CursorInputMapper::dumpParameters(std::string& dump) {
2647 dump += INDENT3 "Parameters:\n";
2648 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002649 toString(mParameters.hasAssociatedDisplay));
2650
2651 switch (mParameters.mode) {
2652 case Parameters::MODE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002653 dump += INDENT4 "Mode: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002654 break;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002655 case Parameters::MODE_POINTER_RELATIVE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002656 dump += INDENT4 "Mode: relative pointer\n";
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002657 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002658 case Parameters::MODE_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002659 dump += INDENT4 "Mode: navigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002660 break;
2661 default:
2662 ALOG_ASSERT(false);
2663 }
2664
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002665 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08002666 toString(mParameters.orientationAware));
2667}
2668
2669void CursorInputMapper::reset(nsecs_t when) {
2670 mButtonState = 0;
2671 mDownTime = 0;
2672
2673 mPointerVelocityControl.reset();
2674 mWheelXVelocityControl.reset();
2675 mWheelYVelocityControl.reset();
2676
2677 mCursorButtonAccumulator.reset(getDevice());
2678 mCursorMotionAccumulator.reset(getDevice());
2679 mCursorScrollAccumulator.reset(getDevice());
2680
2681 InputMapper::reset(when);
2682}
2683
2684void CursorInputMapper::process(const RawEvent* rawEvent) {
2685 mCursorButtonAccumulator.process(rawEvent);
2686 mCursorMotionAccumulator.process(rawEvent);
2687 mCursorScrollAccumulator.process(rawEvent);
2688
2689 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2690 sync(rawEvent->when);
2691 }
2692}
2693
2694void CursorInputMapper::sync(nsecs_t when) {
2695 int32_t lastButtonState = mButtonState;
2696 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2697 mButtonState = currentButtonState;
2698
2699 bool wasDown = isPointerDown(lastButtonState);
2700 bool down = isPointerDown(currentButtonState);
2701 bool downChanged;
2702 if (!wasDown && down) {
2703 mDownTime = when;
2704 downChanged = true;
2705 } else if (wasDown && !down) {
2706 downChanged = true;
2707 } else {
2708 downChanged = false;
2709 }
2710 nsecs_t downTime = mDownTime;
2711 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002712 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2713 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002714
2715 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2716 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2717 bool moved = deltaX != 0 || deltaY != 0;
2718
2719 // Rotate delta according to orientation if needed.
2720 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay
2721 && (deltaX != 0.0f || deltaY != 0.0f)) {
2722 rotateDelta(mOrientation, &deltaX, &deltaY);
2723 }
2724
2725 // Move the pointer.
2726 PointerProperties pointerProperties;
2727 pointerProperties.clear();
2728 pointerProperties.id = 0;
2729 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2730
2731 PointerCoords pointerCoords;
2732 pointerCoords.clear();
2733
2734 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2735 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2736 bool scrolled = vscroll != 0 || hscroll != 0;
2737
Yi Kong9b14ac62018-07-17 13:48:38 -07002738 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2739 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002740
2741 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2742
2743 int32_t displayId;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002744 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002745 if (moved || scrolled || buttonsChanged) {
2746 mPointerController->setPresentation(
2747 PointerControllerInterface::PRESENTATION_POINTER);
2748
2749 if (moved) {
2750 mPointerController->move(deltaX, deltaY);
2751 }
2752
2753 if (buttonsChanged) {
2754 mPointerController->setButtonState(currentButtonState);
2755 }
2756
2757 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2758 }
2759
2760 float x, y;
2761 mPointerController->getPosition(&x, &y);
2762 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2763 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002764 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2765 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002766 displayId = ADISPLAY_ID_DEFAULT;
2767 } else {
2768 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2769 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2770 displayId = ADISPLAY_ID_NONE;
2771 }
2772
2773 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2774
2775 // Moving an external trackball or mouse should wake the device.
2776 // We don't do this for internal cursor devices to prevent them from waking up
2777 // the device in your pocket.
2778 // TODO: Use the input device configuration to control this behavior more finely.
2779 uint32_t policyFlags = 0;
2780 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002781 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002782 }
2783
2784 // Synthesize key down from buttons if needed.
2785 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002786 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002787
2788 // Send motion event.
2789 if (downChanged || moved || scrolled || buttonsChanged) {
2790 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002791 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002792 int32_t motionEventAction;
2793 if (downChanged) {
2794 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002795 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002796 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2797 } else {
2798 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2799 }
2800
Michael Wright7b159c92015-05-14 14:48:03 +01002801 if (buttonsReleased) {
2802 BitSet32 released(buttonsReleased);
2803 while (!released.isEmpty()) {
2804 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2805 buttonState &= ~actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002806 NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002807 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2808 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002809 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002810 mXPrecision, mYPrecision, downTime);
2811 getListener()->notifyMotion(&releaseArgs);
2812 }
2813 }
2814
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002815 NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002816 motionEventAction, 0, 0, metaState, currentButtonState,
2817 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002818 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002819 mXPrecision, mYPrecision, downTime);
2820 getListener()->notifyMotion(&args);
2821
Michael Wright7b159c92015-05-14 14:48:03 +01002822 if (buttonsPressed) {
2823 BitSet32 pressed(buttonsPressed);
2824 while (!pressed.isEmpty()) {
2825 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2826 buttonState |= actionButton;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002827 NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002828 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2829 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002830 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wright7b159c92015-05-14 14:48:03 +01002831 mXPrecision, mYPrecision, downTime);
2832 getListener()->notifyMotion(&pressArgs);
2833 }
2834 }
2835
2836 ALOG_ASSERT(buttonState == currentButtonState);
2837
Michael Wrightd02c5b62014-02-10 15:10:22 -08002838 // Send hover move after UP to tell the application that the mouse is hovering now.
2839 if (motionEventAction == AMOTION_EVENT_ACTION_UP
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002840 && (mSource == AINPUT_SOURCE_MOUSE)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002841 NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002842 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002843 metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002844 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002845 mXPrecision, mYPrecision, downTime);
2846 getListener()->notifyMotion(&hoverArgs);
2847 }
2848
2849 // Send scroll events.
2850 if (scrolled) {
2851 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2852 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2853
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002854 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01002855 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002856 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002857 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08002858 mXPrecision, mYPrecision, downTime);
2859 getListener()->notifyMotion(&scrollArgs);
2860 }
2861 }
2862
2863 // Synthesize key up from buttons if needed.
2864 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002865 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002866
2867 mCursorMotionAccumulator.finishSync();
2868 mCursorScrollAccumulator.finishSync();
2869}
2870
2871int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2872 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2873 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2874 } else {
2875 return AKEY_STATE_UNKNOWN;
2876 }
2877}
2878
2879void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002880 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002881 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2882 }
2883}
2884
Prashant Malani1941ff52015-08-11 18:29:28 -07002885// --- RotaryEncoderInputMapper ---
2886
2887RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) :
Ivan Podogovad437252016-09-29 16:29:55 +01002888 InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002889 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2890}
2891
2892RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {
2893}
2894
2895uint32_t RotaryEncoderInputMapper::getSources() {
2896 return mSource;
2897}
2898
2899void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2900 InputMapper::populateDeviceInfo(info);
2901
2902 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002903 float res = 0.0f;
2904 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2905 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2906 }
2907 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
2908 mScalingFactor)) {
2909 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
2910 "default to 1.0!\n");
2911 mScalingFactor = 1.0f;
2912 }
2913 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
2914 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002915 }
2916}
2917
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002918void RotaryEncoderInputMapper::dump(std::string& dump) {
2919 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2920 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prashant Malani1941ff52015-08-11 18:29:28 -07002921 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
2922}
2923
2924void RotaryEncoderInputMapper::configure(nsecs_t when,
2925 const InputReaderConfiguration* config, uint32_t changes) {
2926 InputMapper::configure(when, config, changes);
2927 if (!changes) {
2928 mRotaryEncoderScrollAccumulator.configure(getDevice());
2929 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07002930 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002931 std::optional<DisplayViewport> internalViewport =
2932 config->getDisplayViewport(ViewportType::VIEWPORT_INTERNAL, "");
2933 if (internalViewport) {
2934 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01002935 } else {
2936 mOrientation = DISPLAY_ORIENTATION_0;
2937 }
2938 }
Prashant Malani1941ff52015-08-11 18:29:28 -07002939}
2940
2941void RotaryEncoderInputMapper::reset(nsecs_t when) {
2942 mRotaryEncoderScrollAccumulator.reset(getDevice());
2943
2944 InputMapper::reset(when);
2945}
2946
2947void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
2948 mRotaryEncoderScrollAccumulator.process(rawEvent);
2949
2950 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2951 sync(rawEvent->when);
2952 }
2953}
2954
2955void RotaryEncoderInputMapper::sync(nsecs_t when) {
2956 PointerCoords pointerCoords;
2957 pointerCoords.clear();
2958
2959 PointerProperties pointerProperties;
2960 pointerProperties.clear();
2961 pointerProperties.id = 0;
2962 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
2963
2964 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
2965 bool scrolled = scroll != 0;
2966
2967 // This is not a pointer, so it's not associated with a display.
2968 int32_t displayId = ADISPLAY_ID_NONE;
2969
2970 // Moving the rotary encoder should wake the device (if specified).
2971 uint32_t policyFlags = 0;
2972 if (scrolled && getDevice()->isExternal()) {
2973 policyFlags |= POLICY_FLAG_WAKE;
2974 }
2975
Ivan Podogovad437252016-09-29 16:29:55 +01002976 if (mOrientation == DISPLAY_ORIENTATION_180) {
2977 scroll = -scroll;
2978 }
2979
Prashant Malani1941ff52015-08-11 18:29:28 -07002980 // Send motion event.
2981 if (scrolled) {
2982 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08002983 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002984
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002985 NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
Prashant Malani1941ff52015-08-11 18:29:28 -07002986 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
2987 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002988 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Prashant Malani1941ff52015-08-11 18:29:28 -07002989 0, 0, 0);
2990 getListener()->notifyMotion(&scrollArgs);
2991 }
2992
2993 mRotaryEncoderScrollAccumulator.finishSync();
2994}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002995
2996// --- TouchInputMapper ---
2997
2998TouchInputMapper::TouchInputMapper(InputDevice* device) :
2999 InputMapper(device),
3000 mSource(0), mDeviceMode(DEVICE_MODE_DISABLED),
3001 mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0),
Michael Wright358bcc72018-08-21 04:01:07 +01003002 mPhysicalWidth(-1), mPhysicalHeight(-1), mPhysicalLeft(0), mPhysicalTop(0),
Michael Wrightd02c5b62014-02-10 15:10:22 -08003003 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {
3004}
3005
3006TouchInputMapper::~TouchInputMapper() {
3007}
3008
3009uint32_t TouchInputMapper::getSources() {
3010 return mSource;
3011}
3012
3013void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3014 InputMapper::populateDeviceInfo(info);
3015
3016 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3017 info->addMotionRange(mOrientedRanges.x);
3018 info->addMotionRange(mOrientedRanges.y);
3019 info->addMotionRange(mOrientedRanges.pressure);
3020
3021 if (mOrientedRanges.haveSize) {
3022 info->addMotionRange(mOrientedRanges.size);
3023 }
3024
3025 if (mOrientedRanges.haveTouchSize) {
3026 info->addMotionRange(mOrientedRanges.touchMajor);
3027 info->addMotionRange(mOrientedRanges.touchMinor);
3028 }
3029
3030 if (mOrientedRanges.haveToolSize) {
3031 info->addMotionRange(mOrientedRanges.toolMajor);
3032 info->addMotionRange(mOrientedRanges.toolMinor);
3033 }
3034
3035 if (mOrientedRanges.haveOrientation) {
3036 info->addMotionRange(mOrientedRanges.orientation);
3037 }
3038
3039 if (mOrientedRanges.haveDistance) {
3040 info->addMotionRange(mOrientedRanges.distance);
3041 }
3042
3043 if (mOrientedRanges.haveTilt) {
3044 info->addMotionRange(mOrientedRanges.tilt);
3045 }
3046
3047 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3048 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3049 0.0f);
3050 }
3051 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3052 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
3053 0.0f);
3054 }
3055 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3056 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3057 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3058 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
3059 x.fuzz, x.resolution);
3060 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
3061 y.fuzz, y.resolution);
3062 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
3063 x.fuzz, x.resolution);
3064 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
3065 y.fuzz, y.resolution);
3066 }
3067 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3068 }
3069}
3070
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003071void TouchInputMapper::dump(std::string& dump) {
3072 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003073 dumpParameters(dump);
3074 dumpVirtualKeys(dump);
3075 dumpRawPointerAxes(dump);
3076 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003077 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003078 dumpSurface(dump);
3079
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003080 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3081 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3082 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3083 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3084 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3085 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3086 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3087 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3088 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3089 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3090 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3091 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3092 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3093 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3094 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3095 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3096 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003097
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003098 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3099 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003100 mLastRawState.rawPointerData.pointerCount);
3101 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3102 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003103 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003104 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3105 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3106 "toolType=%d, isHovering=%s\n", i,
3107 pointer.id, pointer.x, pointer.y, pointer.pressure,
3108 pointer.touchMajor, pointer.touchMinor,
3109 pointer.toolMajor, pointer.toolMinor,
3110 pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance,
3111 pointer.toolType, toString(pointer.isHovering));
3112 }
3113
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003114 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState);
3115 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Michael Wright842500e2015-03-13 17:32:02 -07003116 mLastCookedState.cookedPointerData.pointerCount);
3117 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3118 const PointerProperties& pointerProperties =
3119 mLastCookedState.cookedPointerData.pointerProperties[i];
3120 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003121 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003122 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, "
3123 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3124 "toolType=%d, isHovering=%s\n", i,
3125 pointerProperties.id,
3126 pointerCoords.getX(),
3127 pointerCoords.getY(),
3128 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3129 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3130 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3131 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3132 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3133 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3134 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3135 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3136 pointerProperties.toolType,
Michael Wright842500e2015-03-13 17:32:02 -07003137 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003138 }
3139
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003140 dump += INDENT3 "Stylus Fusion:\n";
3141 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Michael Wright842500e2015-03-13 17:32:02 -07003142 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003143 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3144 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Michael Wright43fd19f2015-04-21 19:02:58 +01003145 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003146 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003147 dumpStylusState(dump, mExternalStylusState);
3148
Michael Wrightd02c5b62014-02-10 15:10:22 -08003149 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003150 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
3151 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003152 mPointerXMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003153 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003154 mPointerYMovementScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003155 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003156 mPointerXZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003157 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003158 mPointerYZoomScale);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003159 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 mPointerGestureMaxSwipeWidth);
3161 }
3162}
3163
Santos Cordonfa5cf462017-04-05 10:37:00 -07003164const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3165 switch (deviceMode) {
3166 case DEVICE_MODE_DISABLED:
3167 return "disabled";
3168 case DEVICE_MODE_DIRECT:
3169 return "direct";
3170 case DEVICE_MODE_UNSCALED:
3171 return "unscaled";
3172 case DEVICE_MODE_NAVIGATION:
3173 return "navigation";
3174 case DEVICE_MODE_POINTER:
3175 return "pointer";
3176 }
3177 return "unknown";
3178}
3179
Michael Wrightd02c5b62014-02-10 15:10:22 -08003180void TouchInputMapper::configure(nsecs_t when,
3181 const InputReaderConfiguration* config, uint32_t changes) {
3182 InputMapper::configure(when, config, changes);
3183
3184 mConfig = *config;
3185
3186 if (!changes) { // first time only
3187 // Configure basic parameters.
3188 configureParameters();
3189
3190 // Configure common accumulators.
3191 mCursorScrollAccumulator.configure(getDevice());
3192 mTouchButtonAccumulator.configure(getDevice());
3193
3194 // Configure absolute axis information.
3195 configureRawPointerAxes();
3196
3197 // Prepare input device calibration.
3198 parseCalibration();
3199 resolveCalibration();
3200 }
3201
Michael Wright842500e2015-03-13 17:32:02 -07003202 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003203 // Update location calibration to reflect current settings
3204 updateAffineTransformation();
3205 }
3206
Michael Wrightd02c5b62014-02-10 15:10:22 -08003207 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3208 // Update pointer speed.
3209 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3210 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3211 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3212 }
3213
3214 bool resetNeeded = false;
3215 if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO
3216 | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT
Michael Wright842500e2015-03-13 17:32:02 -07003217 | InputReaderConfiguration::CHANGE_SHOW_TOUCHES
3218 | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 // Configure device sources, surface dimensions, orientation and
3220 // scaling factors.
3221 configureSurface(when, &resetNeeded);
3222 }
3223
3224 if (changes && resetNeeded) {
3225 // Send reset, unless this is the first time the device has been configured,
3226 // in which case the reader will call reset itself after all mappers are ready.
3227 getDevice()->notifyReset(when);
3228 }
3229}
3230
Michael Wright842500e2015-03-13 17:32:02 -07003231void TouchInputMapper::resolveExternalStylusPresence() {
3232 Vector<InputDeviceInfo> devices;
3233 mContext->getExternalStylusDevices(devices);
3234 mExternalStylusConnected = !devices.isEmpty();
3235
3236 if (!mExternalStylusConnected) {
3237 resetExternalStylus();
3238 }
3239}
3240
Michael Wrightd02c5b62014-02-10 15:10:22 -08003241void TouchInputMapper::configureParameters() {
3242 // Use the pointer presentation mode for devices that do not support distinct
3243 // multitouch. The spot-based presentation relies on being able to accurately
3244 // locate two or more fingers on the touch pad.
3245 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003246 ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003247
3248 String8 gestureModeString;
3249 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
3250 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003251 if (gestureModeString == "single-touch") {
3252 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3253 } else if (gestureModeString == "multi-touch") {
3254 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003255 } else if (gestureModeString != "default") {
3256 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3257 }
3258 }
3259
3260 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3261 // The device is a touch screen.
3262 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3263 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3264 // The device is a pointing device like a track pad.
3265 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3266 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X)
3267 || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
3268 // The device is a cursor device with a touch pad attached.
3269 // By default don't use the touch pad to move the pointer.
3270 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3271 } else {
3272 // The device is a touch pad of unknown purpose.
3273 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3274 }
3275
3276 mParameters.hasButtonUnderPad=
3277 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3278
3279 String8 deviceTypeString;
3280 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
3281 deviceTypeString)) {
3282 if (deviceTypeString == "touchScreen") {
3283 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3284 } else if (deviceTypeString == "touchPad") {
3285 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3286 } else if (deviceTypeString == "touchNavigation") {
3287 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3288 } else if (deviceTypeString == "pointer") {
3289 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3290 } else if (deviceTypeString != "default") {
3291 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3292 }
3293 }
3294
3295 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3296 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
3297 mParameters.orientationAware);
3298
3299 mParameters.hasAssociatedDisplay = false;
3300 mParameters.associatedDisplayIsExternal = false;
3301 if (mParameters.orientationAware
3302 || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3303 || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
3304 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003305 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3306 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003307 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003308 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003309 uniqueDisplayId);
3310 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003311 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003312 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003313
3314 // Initial downs on external touch devices should wake the device.
3315 // Normally we don't do this for internal touch screens to prevent them from waking
3316 // up in your pocket but you can enable it using the input device configuration.
3317 mParameters.wake = getDevice()->isExternal();
3318 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"),
3319 mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003320}
3321
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003322void TouchInputMapper::dumpParameters(std::string& dump) {
3323 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003324
3325 switch (mParameters.gestureMode) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003326 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003327 dump += INDENT4 "GestureMode: single-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003328 break;
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003329 case Parameters::GESTURE_MODE_MULTI_TOUCH:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003330 dump += INDENT4 "GestureMode: multi-touch\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003331 break;
3332 default:
3333 assert(false);
3334 }
3335
3336 switch (mParameters.deviceType) {
3337 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003338 dump += INDENT4 "DeviceType: touchScreen\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003339 break;
3340 case Parameters::DEVICE_TYPE_TOUCH_PAD:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003341 dump += INDENT4 "DeviceType: touchPad\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003342 break;
3343 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003344 dump += INDENT4 "DeviceType: touchNavigation\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003345 break;
3346 case Parameters::DEVICE_TYPE_POINTER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003347 dump += INDENT4 "DeviceType: pointer\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003348 break;
3349 default:
3350 ALOG_ASSERT(false);
3351 }
3352
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003353 dump += StringPrintf(
Santos Cordonfa5cf462017-04-05 10:37:00 -07003354 INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, displayId='%s'\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003355 toString(mParameters.hasAssociatedDisplay),
Santos Cordonfa5cf462017-04-05 10:37:00 -07003356 toString(mParameters.associatedDisplayIsExternal),
3357 mParameters.uniqueDisplayId.c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003358 dump += StringPrintf(INDENT4 "OrientationAware: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08003359 toString(mParameters.orientationAware));
3360}
3361
3362void TouchInputMapper::configureRawPointerAxes() {
3363 mRawPointerAxes.clear();
3364}
3365
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003366void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3367 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003368 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3369 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3370 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3371 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3372 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3373 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3374 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3375 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3376 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3377 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3378 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3379 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3380 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3381}
3382
Michael Wright842500e2015-03-13 17:32:02 -07003383bool TouchInputMapper::hasExternalStylus() const {
3384 return mExternalStylusConnected;
3385}
3386
Michael Wrightd02c5b62014-02-10 15:10:22 -08003387void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3388 int32_t oldDeviceMode = mDeviceMode;
3389
Michael Wright842500e2015-03-13 17:32:02 -07003390 resolveExternalStylusPresence();
3391
Michael Wrightd02c5b62014-02-10 15:10:22 -08003392 // Determine device mode.
3393 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER
3394 && mConfig.pointerGesturesEnabled) {
3395 mSource = AINPUT_SOURCE_MOUSE;
3396 mDeviceMode = DEVICE_MODE_POINTER;
3397 if (hasStylus()) {
3398 mSource |= AINPUT_SOURCE_STYLUS;
3399 }
3400 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN
3401 && mParameters.hasAssociatedDisplay) {
3402 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3403 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003404 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405 mSource |= AINPUT_SOURCE_STYLUS;
3406 }
Michael Wright2f78b682015-06-12 15:25:08 +01003407 if (hasExternalStylus()) {
3408 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3409 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003410 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3411 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3412 mDeviceMode = DEVICE_MODE_NAVIGATION;
3413 } else {
3414 mSource = AINPUT_SOURCE_TOUCHPAD;
3415 mDeviceMode = DEVICE_MODE_UNSCALED;
3416 }
3417
3418 // Ensure we have valid X and Y axes.
3419 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
3420 ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! "
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003421 "The device will be inoperable.", getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003422 mDeviceMode = DEVICE_MODE_DISABLED;
3423 return;
3424 }
3425
3426 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003427 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3428 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003429
3430 // Get associated display dimensions.
3431 DisplayViewport newViewport;
3432 if (mParameters.hasAssociatedDisplay) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003433 std::string uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003434 ViewportType viewportTypeToUse;
3435
3436 if (mParameters.associatedDisplayIsExternal) {
3437 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003438 } else if (!mParameters.uniqueDisplayId.empty()) {
Santos Cordonfa5cf462017-04-05 10:37:00 -07003439 // If the IDC file specified a unique display Id, then it expects to be linked to a
3440 // virtual display with the same unique ID.
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003441 uniqueDisplayId = mParameters.uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003442 viewportTypeToUse = ViewportType::VIEWPORT_VIRTUAL;
3443 } else {
3444 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3445 }
3446
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003447 std::optional<DisplayViewport> viewportToUse =
3448 mConfig.getDisplayViewport(viewportTypeToUse, uniqueDisplayId);
3449 if (!viewportToUse) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003450 ALOGI(INDENT "Touch device '%s' could not query the properties of its associated "
3451 "display. The device will be inoperable until the display size "
3452 "becomes available.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003453 getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003454 mDeviceMode = DEVICE_MODE_DISABLED;
3455 return;
3456 }
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003457 newViewport = *viewportToUse;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003458 } else {
3459 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3460 }
3461 bool viewportChanged = mViewport != newViewport;
3462 if (viewportChanged) {
3463 mViewport = newViewport;
3464
3465 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3466 // Convert rotated viewport to natural surface coordinates.
3467 int32_t naturalLogicalWidth, naturalLogicalHeight;
3468 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3469 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3470 int32_t naturalDeviceWidth, naturalDeviceHeight;
3471 switch (mViewport.orientation) {
3472 case DISPLAY_ORIENTATION_90:
3473 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3474 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3475 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3476 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3477 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3478 naturalPhysicalTop = mViewport.physicalLeft;
3479 naturalDeviceWidth = mViewport.deviceHeight;
3480 naturalDeviceHeight = mViewport.deviceWidth;
3481 break;
3482 case DISPLAY_ORIENTATION_180:
3483 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3484 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3485 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3486 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3487 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3488 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3489 naturalDeviceWidth = mViewport.deviceWidth;
3490 naturalDeviceHeight = mViewport.deviceHeight;
3491 break;
3492 case DISPLAY_ORIENTATION_270:
3493 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3494 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3495 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3496 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3497 naturalPhysicalLeft = mViewport.physicalTop;
3498 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3499 naturalDeviceWidth = mViewport.deviceHeight;
3500 naturalDeviceHeight = mViewport.deviceWidth;
3501 break;
3502 case DISPLAY_ORIENTATION_0:
3503 default:
3504 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3505 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3506 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3507 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3508 naturalPhysicalLeft = mViewport.physicalLeft;
3509 naturalPhysicalTop = mViewport.physicalTop;
3510 naturalDeviceWidth = mViewport.deviceWidth;
3511 naturalDeviceHeight = mViewport.deviceHeight;
3512 break;
3513 }
3514
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003515 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3516 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3517 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3518 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3519 }
3520
Michael Wright358bcc72018-08-21 04:01:07 +01003521 mPhysicalWidth = naturalPhysicalWidth;
3522 mPhysicalHeight = naturalPhysicalHeight;
3523 mPhysicalLeft = naturalPhysicalLeft;
3524 mPhysicalTop = naturalPhysicalTop;
3525
Michael Wrightd02c5b62014-02-10 15:10:22 -08003526 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3527 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3528 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3529 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3530
3531 mSurfaceOrientation = mParameters.orientationAware ?
3532 mViewport.orientation : DISPLAY_ORIENTATION_0;
3533 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003534 mPhysicalWidth = rawWidth;
3535 mPhysicalHeight = rawHeight;
3536 mPhysicalLeft = 0;
3537 mPhysicalTop = 0;
3538
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 mSurfaceWidth = rawWidth;
3540 mSurfaceHeight = rawHeight;
3541 mSurfaceLeft = 0;
3542 mSurfaceTop = 0;
3543 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3544 }
3545 }
3546
3547 // If moving between pointer modes, need to reset some state.
3548 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3549 if (deviceModeChanged) {
3550 mOrientedRanges.clear();
3551 }
3552
3553 // Create pointer controller if needed.
3554 if (mDeviceMode == DEVICE_MODE_POINTER ||
3555 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Yi Kong9b14ac62018-07-17 13:48:38 -07003556 if (mPointerController == nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003557 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3558 }
3559 } else {
3560 mPointerController.clear();
3561 }
3562
3563 if (viewportChanged || deviceModeChanged) {
3564 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
3565 "display id %d",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003566 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
3568
3569 // Configure X and Y factors.
3570 mXScale = float(mSurfaceWidth) / rawWidth;
3571 mYScale = float(mSurfaceHeight) / rawHeight;
3572 mXTranslate = -mSurfaceLeft;
3573 mYTranslate = -mSurfaceTop;
3574 mXPrecision = 1.0f / mXScale;
3575 mYPrecision = 1.0f / mYScale;
3576
3577 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3578 mOrientedRanges.x.source = mSource;
3579 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3580 mOrientedRanges.y.source = mSource;
3581
3582 configureVirtualKeys();
3583
3584 // Scale factor for terms that are not oriented in a particular axis.
3585 // If the pixels are square then xScale == yScale otherwise we fake it
3586 // by choosing an average.
3587 mGeometricScale = avg(mXScale, mYScale);
3588
3589 // Size of diagonal axis.
3590 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3591
3592 // Size factors.
3593 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
3594 if (mRawPointerAxes.touchMajor.valid
3595 && mRawPointerAxes.touchMajor.maxValue != 0) {
3596 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
3597 } else if (mRawPointerAxes.toolMajor.valid
3598 && mRawPointerAxes.toolMajor.maxValue != 0) {
3599 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3600 } else {
3601 mSizeScale = 0.0f;
3602 }
3603
3604 mOrientedRanges.haveTouchSize = true;
3605 mOrientedRanges.haveToolSize = true;
3606 mOrientedRanges.haveSize = true;
3607
3608 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3609 mOrientedRanges.touchMajor.source = mSource;
3610 mOrientedRanges.touchMajor.min = 0;
3611 mOrientedRanges.touchMajor.max = diagonalSize;
3612 mOrientedRanges.touchMajor.flat = 0;
3613 mOrientedRanges.touchMajor.fuzz = 0;
3614 mOrientedRanges.touchMajor.resolution = 0;
3615
3616 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3617 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3618
3619 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3620 mOrientedRanges.toolMajor.source = mSource;
3621 mOrientedRanges.toolMajor.min = 0;
3622 mOrientedRanges.toolMajor.max = diagonalSize;
3623 mOrientedRanges.toolMajor.flat = 0;
3624 mOrientedRanges.toolMajor.fuzz = 0;
3625 mOrientedRanges.toolMajor.resolution = 0;
3626
3627 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3628 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3629
3630 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3631 mOrientedRanges.size.source = mSource;
3632 mOrientedRanges.size.min = 0;
3633 mOrientedRanges.size.max = 1.0;
3634 mOrientedRanges.size.flat = 0;
3635 mOrientedRanges.size.fuzz = 0;
3636 mOrientedRanges.size.resolution = 0;
3637 } else {
3638 mSizeScale = 0.0f;
3639 }
3640
3641 // Pressure factors.
3642 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003643 float pressureMax = 1.0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003644 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL
3645 || mCalibration.pressureCalibration
3646 == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
3647 if (mCalibration.havePressureScale) {
3648 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003649 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003650 } else if (mRawPointerAxes.pressure.valid
3651 && mRawPointerAxes.pressure.maxValue != 0) {
3652 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3653 }
3654 }
3655
3656 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3657 mOrientedRanges.pressure.source = mSource;
3658 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003659 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003660 mOrientedRanges.pressure.flat = 0;
3661 mOrientedRanges.pressure.fuzz = 0;
3662 mOrientedRanges.pressure.resolution = 0;
3663
3664 // Tilt
3665 mTiltXCenter = 0;
3666 mTiltXScale = 0;
3667 mTiltYCenter = 0;
3668 mTiltYScale = 0;
3669 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3670 if (mHaveTilt) {
3671 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue,
3672 mRawPointerAxes.tiltX.maxValue);
3673 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue,
3674 mRawPointerAxes.tiltY.maxValue);
3675 mTiltXScale = M_PI / 180;
3676 mTiltYScale = M_PI / 180;
3677
3678 mOrientedRanges.haveTilt = true;
3679
3680 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3681 mOrientedRanges.tilt.source = mSource;
3682 mOrientedRanges.tilt.min = 0;
3683 mOrientedRanges.tilt.max = M_PI_2;
3684 mOrientedRanges.tilt.flat = 0;
3685 mOrientedRanges.tilt.fuzz = 0;
3686 mOrientedRanges.tilt.resolution = 0;
3687 }
3688
3689 // Orientation
3690 mOrientationScale = 0;
3691 if (mHaveTilt) {
3692 mOrientedRanges.haveOrientation = true;
3693
3694 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3695 mOrientedRanges.orientation.source = mSource;
3696 mOrientedRanges.orientation.min = -M_PI;
3697 mOrientedRanges.orientation.max = M_PI;
3698 mOrientedRanges.orientation.flat = 0;
3699 mOrientedRanges.orientation.fuzz = 0;
3700 mOrientedRanges.orientation.resolution = 0;
3701 } else if (mCalibration.orientationCalibration !=
3702 Calibration::ORIENTATION_CALIBRATION_NONE) {
3703 if (mCalibration.orientationCalibration
3704 == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
3705 if (mRawPointerAxes.orientation.valid) {
3706 if (mRawPointerAxes.orientation.maxValue > 0) {
3707 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3708 } else if (mRawPointerAxes.orientation.minValue < 0) {
3709 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3710 } else {
3711 mOrientationScale = 0;
3712 }
3713 }
3714 }
3715
3716 mOrientedRanges.haveOrientation = true;
3717
3718 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3719 mOrientedRanges.orientation.source = mSource;
3720 mOrientedRanges.orientation.min = -M_PI_2;
3721 mOrientedRanges.orientation.max = M_PI_2;
3722 mOrientedRanges.orientation.flat = 0;
3723 mOrientedRanges.orientation.fuzz = 0;
3724 mOrientedRanges.orientation.resolution = 0;
3725 }
3726
3727 // Distance
3728 mDistanceScale = 0;
3729 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
3730 if (mCalibration.distanceCalibration
3731 == Calibration::DISTANCE_CALIBRATION_SCALED) {
3732 if (mCalibration.haveDistanceScale) {
3733 mDistanceScale = mCalibration.distanceScale;
3734 } else {
3735 mDistanceScale = 1.0f;
3736 }
3737 }
3738
3739 mOrientedRanges.haveDistance = true;
3740
3741 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3742 mOrientedRanges.distance.source = mSource;
3743 mOrientedRanges.distance.min =
3744 mRawPointerAxes.distance.minValue * mDistanceScale;
3745 mOrientedRanges.distance.max =
3746 mRawPointerAxes.distance.maxValue * mDistanceScale;
3747 mOrientedRanges.distance.flat = 0;
3748 mOrientedRanges.distance.fuzz =
3749 mRawPointerAxes.distance.fuzz * mDistanceScale;
3750 mOrientedRanges.distance.resolution = 0;
3751 }
3752
3753 // Compute oriented precision, scales and ranges.
3754 // Note that the maximum value reported is an inclusive maximum value so it is one
3755 // unit less than the total width or height of surface.
3756 switch (mSurfaceOrientation) {
3757 case DISPLAY_ORIENTATION_90:
3758 case DISPLAY_ORIENTATION_270:
3759 mOrientedXPrecision = mYPrecision;
3760 mOrientedYPrecision = mXPrecision;
3761
3762 mOrientedRanges.x.min = mYTranslate;
3763 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3764 mOrientedRanges.x.flat = 0;
3765 mOrientedRanges.x.fuzz = 0;
3766 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
3767
3768 mOrientedRanges.y.min = mXTranslate;
3769 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3770 mOrientedRanges.y.flat = 0;
3771 mOrientedRanges.y.fuzz = 0;
3772 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3773 break;
3774
3775 default:
3776 mOrientedXPrecision = mXPrecision;
3777 mOrientedYPrecision = mYPrecision;
3778
3779 mOrientedRanges.x.min = mXTranslate;
3780 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3781 mOrientedRanges.x.flat = 0;
3782 mOrientedRanges.x.fuzz = 0;
3783 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
3784
3785 mOrientedRanges.y.min = mYTranslate;
3786 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3787 mOrientedRanges.y.flat = 0;
3788 mOrientedRanges.y.fuzz = 0;
3789 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3790 break;
3791 }
3792
Jason Gerecke71b16e82014-03-10 09:47:59 -07003793 // Location
3794 updateAffineTransformation();
3795
Michael Wrightd02c5b62014-02-10 15:10:22 -08003796 if (mDeviceMode == DEVICE_MODE_POINTER) {
3797 // Compute pointer gesture detection parameters.
3798 float rawDiagonal = hypotf(rawWidth, rawHeight);
3799 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3800
3801 // Scale movements such that one whole swipe of the touch pad covers a
3802 // given area relative to the diagonal size of the display when no acceleration
3803 // is applied.
3804 // Assume that the touch pad has a square aspect ratio such that movements in
3805 // X and Y of the same number of raw units cover the same physical distance.
3806 mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio
3807 * displayDiagonal / rawDiagonal;
3808 mPointerYMovementScale = mPointerXMovementScale;
3809
3810 // Scale zooms to cover a smaller range of the display than movements do.
3811 // This value determines the area around the pointer that is affected by freeform
3812 // pointer gestures.
3813 mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio
3814 * displayDiagonal / rawDiagonal;
3815 mPointerYZoomScale = mPointerXZoomScale;
3816
3817 // Max width between pointers to detect a swipe gesture is more than some fraction
3818 // of the diagonal axis of the touch pad. Touches that are wider than this are
3819 // translated into freeform gestures.
3820 mPointerGestureMaxSwipeWidth =
3821 mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
3822
3823 // Abort current pointer usages because the state has changed.
3824 abortPointerUsage(when, 0 /*policyFlags*/);
3825 }
3826
3827 // Inform the dispatcher about the changes.
3828 *outResetNeeded = true;
3829 bumpGeneration();
3830 }
3831}
3832
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003833void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003834 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003835 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3836 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3837 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3838 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003839 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3840 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3841 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3842 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003843 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003844}
3845
3846void TouchInputMapper::configureVirtualKeys() {
3847 Vector<VirtualKeyDefinition> virtualKeyDefinitions;
3848 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3849
3850 mVirtualKeys.clear();
3851
3852 if (virtualKeyDefinitions.size() == 0) {
3853 return;
3854 }
3855
3856 mVirtualKeys.setCapacity(virtualKeyDefinitions.size());
3857
3858 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3859 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003860 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3861 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003862
3863 for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) {
3864 const VirtualKeyDefinition& virtualKeyDefinition =
3865 virtualKeyDefinitions[i];
3866
3867 mVirtualKeys.add();
3868 VirtualKey& virtualKey = mVirtualKeys.editTop();
3869
3870 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3871 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003872 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003873 uint32_t flags;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003874 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0,
3875 &keyCode, &dummyKeyMetaState, &flags)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003876 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring",
3877 virtualKey.scanCode);
3878 mVirtualKeys.pop(); // drop the key
3879 continue;
3880 }
3881
3882 virtualKey.keyCode = keyCode;
3883 virtualKey.flags = flags;
3884
3885 // convert the key definition's display coordinates into touch coordinates for a hit box
3886 int32_t halfWidth = virtualKeyDefinition.width / 2;
3887 int32_t halfHeight = virtualKeyDefinition.height / 2;
3888
3889 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth)
3890 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3891 virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth)
3892 * touchScreenWidth / mSurfaceWidth + touchScreenLeft;
3893 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight)
3894 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3895 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight)
3896 * touchScreenHeight / mSurfaceHeight + touchScreenTop;
3897 }
3898}
3899
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003900void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003901 if (!mVirtualKeys.isEmpty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003902 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003903
3904 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
3905 const VirtualKey& virtualKey = mVirtualKeys.itemAt(i);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003906 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08003907 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
3908 i, virtualKey.scanCode, virtualKey.keyCode,
3909 virtualKey.hitLeft, virtualKey.hitRight,
3910 virtualKey.hitTop, virtualKey.hitBottom);
3911 }
3912 }
3913}
3914
3915void TouchInputMapper::parseCalibration() {
3916 const PropertyMap& in = getDevice()->getConfiguration();
3917 Calibration& out = mCalibration;
3918
3919 // Size
3920 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
3921 String8 sizeCalibrationString;
3922 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
3923 if (sizeCalibrationString == "none") {
3924 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
3925 } else if (sizeCalibrationString == "geometric") {
3926 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
3927 } else if (sizeCalibrationString == "diameter") {
3928 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
3929 } else if (sizeCalibrationString == "box") {
3930 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
3931 } else if (sizeCalibrationString == "area") {
3932 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
3933 } else if (sizeCalibrationString != "default") {
3934 ALOGW("Invalid value for touch.size.calibration: '%s'",
3935 sizeCalibrationString.string());
3936 }
3937 }
3938
3939 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"),
3940 out.sizeScale);
3941 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"),
3942 out.sizeBias);
3943 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"),
3944 out.sizeIsSummed);
3945
3946 // Pressure
3947 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
3948 String8 pressureCalibrationString;
3949 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
3950 if (pressureCalibrationString == "none") {
3951 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
3952 } else if (pressureCalibrationString == "physical") {
3953 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
3954 } else if (pressureCalibrationString == "amplitude") {
3955 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
3956 } else if (pressureCalibrationString != "default") {
3957 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
3958 pressureCalibrationString.string());
3959 }
3960 }
3961
3962 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"),
3963 out.pressureScale);
3964
3965 // Orientation
3966 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
3967 String8 orientationCalibrationString;
3968 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
3969 if (orientationCalibrationString == "none") {
3970 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
3971 } else if (orientationCalibrationString == "interpolated") {
3972 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
3973 } else if (orientationCalibrationString == "vector") {
3974 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
3975 } else if (orientationCalibrationString != "default") {
3976 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
3977 orientationCalibrationString.string());
3978 }
3979 }
3980
3981 // Distance
3982 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
3983 String8 distanceCalibrationString;
3984 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
3985 if (distanceCalibrationString == "none") {
3986 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
3987 } else if (distanceCalibrationString == "scaled") {
3988 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
3989 } else if (distanceCalibrationString != "default") {
3990 ALOGW("Invalid value for touch.distance.calibration: '%s'",
3991 distanceCalibrationString.string());
3992 }
3993 }
3994
3995 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"),
3996 out.distanceScale);
3997
3998 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
3999 String8 coverageCalibrationString;
4000 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4001 if (coverageCalibrationString == "none") {
4002 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4003 } else if (coverageCalibrationString == "box") {
4004 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4005 } else if (coverageCalibrationString != "default") {
4006 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
4007 coverageCalibrationString.string());
4008 }
4009 }
4010}
4011
4012void TouchInputMapper::resolveCalibration() {
4013 // Size
4014 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4015 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4016 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4017 }
4018 } else {
4019 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4020 }
4021
4022 // Pressure
4023 if (mRawPointerAxes.pressure.valid) {
4024 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4025 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4026 }
4027 } else {
4028 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4029 }
4030
4031 // Orientation
4032 if (mRawPointerAxes.orientation.valid) {
4033 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4034 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4035 }
4036 } else {
4037 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4038 }
4039
4040 // Distance
4041 if (mRawPointerAxes.distance.valid) {
4042 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4043 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4044 }
4045 } else {
4046 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4047 }
4048
4049 // Coverage
4050 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4051 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4052 }
4053}
4054
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004055void TouchInputMapper::dumpCalibration(std::string& dump) {
4056 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004057
4058 // Size
4059 switch (mCalibration.sizeCalibration) {
4060 case Calibration::SIZE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004061 dump += INDENT4 "touch.size.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004062 break;
4063 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004064 dump += INDENT4 "touch.size.calibration: geometric\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004065 break;
4066 case Calibration::SIZE_CALIBRATION_DIAMETER:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004067 dump += INDENT4 "touch.size.calibration: diameter\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 break;
4069 case Calibration::SIZE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004070 dump += INDENT4 "touch.size.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004071 break;
4072 case Calibration::SIZE_CALIBRATION_AREA:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004073 dump += INDENT4 "touch.size.calibration: area\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004074 break;
4075 default:
4076 ALOG_ASSERT(false);
4077 }
4078
4079 if (mCalibration.haveSizeScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004080 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004081 mCalibration.sizeScale);
4082 }
4083
4084 if (mCalibration.haveSizeBias) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004085 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086 mCalibration.sizeBias);
4087 }
4088
4089 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004090 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004091 toString(mCalibration.sizeIsSummed));
4092 }
4093
4094 // Pressure
4095 switch (mCalibration.pressureCalibration) {
4096 case Calibration::PRESSURE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004097 dump += INDENT4 "touch.pressure.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004098 break;
4099 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004100 dump += INDENT4 "touch.pressure.calibration: physical\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004101 break;
4102 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004103 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004104 break;
4105 default:
4106 ALOG_ASSERT(false);
4107 }
4108
4109 if (mCalibration.havePressureScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004110 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004111 mCalibration.pressureScale);
4112 }
4113
4114 // Orientation
4115 switch (mCalibration.orientationCalibration) {
4116 case Calibration::ORIENTATION_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004117 dump += INDENT4 "touch.orientation.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004118 break;
4119 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004120 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004121 break;
4122 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004123 dump += INDENT4 "touch.orientation.calibration: vector\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004124 break;
4125 default:
4126 ALOG_ASSERT(false);
4127 }
4128
4129 // Distance
4130 switch (mCalibration.distanceCalibration) {
4131 case Calibration::DISTANCE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004132 dump += INDENT4 "touch.distance.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004133 break;
4134 case Calibration::DISTANCE_CALIBRATION_SCALED:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004135 dump += INDENT4 "touch.distance.calibration: scaled\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004136 break;
4137 default:
4138 ALOG_ASSERT(false);
4139 }
4140
4141 if (mCalibration.haveDistanceScale) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004142 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n",
Michael Wrightd02c5b62014-02-10 15:10:22 -08004143 mCalibration.distanceScale);
4144 }
4145
4146 switch (mCalibration.coverageCalibration) {
4147 case Calibration::COVERAGE_CALIBRATION_NONE:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004148 dump += INDENT4 "touch.coverage.calibration: none\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004149 break;
4150 case Calibration::COVERAGE_CALIBRATION_BOX:
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004151 dump += INDENT4 "touch.coverage.calibration: box\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004152 break;
4153 default:
4154 ALOG_ASSERT(false);
4155 }
4156}
4157
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004158void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4159 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004160
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004161 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4162 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4163 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4164 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4165 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4166 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004167}
4168
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004169void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004170 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
4171 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004172}
4173
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174void TouchInputMapper::reset(nsecs_t when) {
4175 mCursorButtonAccumulator.reset(getDevice());
4176 mCursorScrollAccumulator.reset(getDevice());
4177 mTouchButtonAccumulator.reset(getDevice());
4178
4179 mPointerVelocityControl.reset();
4180 mWheelXVelocityControl.reset();
4181 mWheelYVelocityControl.reset();
4182
Michael Wright842500e2015-03-13 17:32:02 -07004183 mRawStatesPending.clear();
4184 mCurrentRawState.clear();
4185 mCurrentCookedState.clear();
4186 mLastRawState.clear();
4187 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004188 mPointerUsage = POINTER_USAGE_NONE;
4189 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004190 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004191 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004192 mDownTime = 0;
4193
4194 mCurrentVirtualKey.down = false;
4195
4196 mPointerGesture.reset();
4197 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004198 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004199
Yi Kong9b14ac62018-07-17 13:48:38 -07004200 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004201 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4202 mPointerController->clearSpots();
4203 }
4204
4205 InputMapper::reset(when);
4206}
4207
Michael Wright842500e2015-03-13 17:32:02 -07004208void TouchInputMapper::resetExternalStylus() {
4209 mExternalStylusState.clear();
4210 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004211 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004212 mExternalStylusDataPending = false;
4213}
4214
Michael Wright43fd19f2015-04-21 19:02:58 +01004215void TouchInputMapper::clearStylusDataPendingFlags() {
4216 mExternalStylusDataPending = false;
4217 mExternalStylusFusionTimeout = LLONG_MAX;
4218}
4219
Michael Wrightd02c5b62014-02-10 15:10:22 -08004220void TouchInputMapper::process(const RawEvent* rawEvent) {
4221 mCursorButtonAccumulator.process(rawEvent);
4222 mCursorScrollAccumulator.process(rawEvent);
4223 mTouchButtonAccumulator.process(rawEvent);
4224
4225 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4226 sync(rawEvent->when);
4227 }
4228}
4229
4230void TouchInputMapper::sync(nsecs_t when) {
Michael Wright842500e2015-03-13 17:32:02 -07004231 const RawState* last = mRawStatesPending.isEmpty() ?
4232 &mCurrentRawState : &mRawStatesPending.top();
4233
4234 // Push a new state.
4235 mRawStatesPending.push();
4236 RawState* next = &mRawStatesPending.editTop();
4237 next->clear();
4238 next->when = when;
4239
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 // Sync button state.
Michael Wright842500e2015-03-13 17:32:02 -07004241 next->buttonState = mTouchButtonAccumulator.getButtonState()
Michael Wrightd02c5b62014-02-10 15:10:22 -08004242 | mCursorButtonAccumulator.getButtonState();
4243
Michael Wright842500e2015-03-13 17:32:02 -07004244 // Sync scroll
4245 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4246 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004247 mCursorScrollAccumulator.finishSync();
4248
Michael Wright842500e2015-03-13 17:32:02 -07004249 // Sync touch
4250 syncTouch(when, next);
4251
4252 // Assign pointer ids.
4253 if (!mHavePointerIds) {
4254 assignPointerIds(last, next);
4255 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004256
4257#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004258 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
4259 "hovering ids 0x%08x -> 0x%08x",
4260 last->rawPointerData.pointerCount,
4261 next->rawPointerData.pointerCount,
4262 last->rawPointerData.touchingIdBits.value,
4263 next->rawPointerData.touchingIdBits.value,
4264 last->rawPointerData.hoveringIdBits.value,
4265 next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004266#endif
4267
Michael Wright842500e2015-03-13 17:32:02 -07004268 processRawTouches(false /*timeout*/);
4269}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004270
Michael Wright842500e2015-03-13 17:32:02 -07004271void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004272 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4273 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004274 mCurrentRawState.clear();
4275 mRawStatesPending.clear();
4276 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 }
4278
Michael Wright842500e2015-03-13 17:32:02 -07004279 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4280 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4281 // touching the current state will only observe the events that have been dispatched to the
4282 // rest of the pipeline.
4283 const size_t N = mRawStatesPending.size();
4284 size_t count;
4285 for(count = 0; count < N; count++) {
4286 const RawState& next = mRawStatesPending[count];
4287
4288 // A failure to assign the stylus id means that we're waiting on stylus data
4289 // and so should defer the rest of the pipeline.
4290 if (assignExternalStylusId(next, timeout)) {
4291 break;
4292 }
4293
4294 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004295 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004296 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004297 if (mCurrentRawState.when < mLastRawState.when) {
4298 mCurrentRawState.when = mLastRawState.when;
4299 }
Michael Wright842500e2015-03-13 17:32:02 -07004300 cookAndDispatch(mCurrentRawState.when);
4301 }
4302 if (count != 0) {
4303 mRawStatesPending.removeItemsAt(0, count);
4304 }
4305
Michael Wright842500e2015-03-13 17:32:02 -07004306 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004307 if (timeout) {
4308 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4309 clearStylusDataPendingFlags();
4310 mCurrentRawState.copyFrom(mLastRawState);
4311#if DEBUG_STYLUS_FUSION
4312 ALOGD("Timeout expired, synthesizing event with new stylus data");
4313#endif
4314 cookAndDispatch(when);
4315 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4316 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4317 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4318 }
Michael Wright842500e2015-03-13 17:32:02 -07004319 }
4320}
4321
4322void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4323 // Always start with a clean state.
4324 mCurrentCookedState.clear();
4325
4326 // Apply stylus buttons to current raw state.
4327 applyExternalStylusButtonState(when);
4328
4329 // Handle policy on initial down or hover events.
4330 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4331 && mCurrentRawState.rawPointerData.pointerCount != 0;
4332
4333 uint32_t policyFlags = 0;
4334 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4335 if (initialDown || buttonsPressed) {
4336 // If this is a touch screen, hide the pointer on an initial down.
4337 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4338 getContext()->fadePointer();
4339 }
4340
4341 if (mParameters.wake) {
4342 policyFlags |= POLICY_FLAG_WAKE;
4343 }
4344 }
4345
4346 // Consume raw off-screen touches before cooking pointer data.
4347 // If touches are consumed, subsequent code will not receive any pointer data.
4348 if (consumeRawTouches(when, policyFlags)) {
4349 mCurrentRawState.rawPointerData.clear();
4350 }
4351
4352 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4353 // with cooked pointer data that has the same ids and indices as the raw data.
4354 // The following code can use either the raw or cooked data, as needed.
4355 cookPointerData();
4356
4357 // Apply stylus pressure to current cooked state.
4358 applyExternalStylusTouchState(when);
4359
4360 // Synthesize key down from raw buttons if needed.
4361 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004362 mViewport.displayId, policyFlags,
4363 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004364
4365 // Dispatch the touches either directly or by translation through a pointer on screen.
4366 if (mDeviceMode == DEVICE_MODE_POINTER) {
4367 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits);
4368 !idBits.isEmpty(); ) {
4369 uint32_t id = idBits.clearFirstMarkedBit();
4370 const RawPointerData::Pointer& pointer =
4371 mCurrentRawState.rawPointerData.pointerForId(id);
4372 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4373 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4374 mCurrentCookedState.stylusIdBits.markBit(id);
4375 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER
4376 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4377 mCurrentCookedState.fingerIdBits.markBit(id);
4378 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4379 mCurrentCookedState.mouseIdBits.markBit(id);
4380 }
4381 }
4382 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits);
4383 !idBits.isEmpty(); ) {
4384 uint32_t id = idBits.clearFirstMarkedBit();
4385 const RawPointerData::Pointer& pointer =
4386 mCurrentRawState.rawPointerData.pointerForId(id);
4387 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS
4388 || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
4389 mCurrentCookedState.stylusIdBits.markBit(id);
4390 }
4391 }
4392
4393 // Stylus takes precedence over all tools, then mouse, then finger.
4394 PointerUsage pointerUsage = mPointerUsage;
4395 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4396 mCurrentCookedState.mouseIdBits.clear();
4397 mCurrentCookedState.fingerIdBits.clear();
4398 pointerUsage = POINTER_USAGE_STYLUS;
4399 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4400 mCurrentCookedState.fingerIdBits.clear();
4401 pointerUsage = POINTER_USAGE_MOUSE;
4402 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
4403 isPointerDown(mCurrentRawState.buttonState)) {
4404 pointerUsage = POINTER_USAGE_GESTURES;
4405 }
4406
4407 dispatchPointerUsage(when, policyFlags, pointerUsage);
4408 } else {
4409 if (mDeviceMode == DEVICE_MODE_DIRECT
Yi Kong9b14ac62018-07-17 13:48:38 -07004410 && mConfig.showTouches && mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004411 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4412 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4413
4414 mPointerController->setButtonState(mCurrentRawState.buttonState);
4415 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
4416 mCurrentCookedState.cookedPointerData.idToIndex,
4417 mCurrentCookedState.cookedPointerData.touchingIdBits);
4418 }
4419
Michael Wright8e812822015-06-22 16:18:21 +01004420 if (!mCurrentMotionAborted) {
4421 dispatchButtonRelease(when, policyFlags);
4422 dispatchHoverExit(when, policyFlags);
4423 dispatchTouches(when, policyFlags);
4424 dispatchHoverEnterAndMove(when, policyFlags);
4425 dispatchButtonPress(when, policyFlags);
4426 }
4427
4428 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4429 mCurrentMotionAborted = false;
4430 }
Michael Wright842500e2015-03-13 17:32:02 -07004431 }
4432
4433 // Synthesize key up from raw buttons if needed.
4434 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004435 mViewport.displayId, policyFlags,
4436 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004437
4438 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004439 mCurrentRawState.rawVScroll = 0;
4440 mCurrentRawState.rawHScroll = 0;
4441
4442 // Copy current touch to last touch in preparation for the next cycle.
4443 mLastRawState.copyFrom(mCurrentRawState);
4444 mLastCookedState.copyFrom(mCurrentCookedState);
4445}
4446
4447void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004448 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004449 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4450 }
4451}
4452
4453void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004454 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4455 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004456
Michael Wright53dca3a2015-04-23 17:39:53 +01004457 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4458 float pressure = mExternalStylusState.pressure;
4459 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4460 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4461 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4462 }
4463 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4464 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4465
4466 PointerProperties& properties =
4467 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004468 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4469 properties.toolType = mExternalStylusState.toolType;
4470 }
4471 }
4472}
4473
4474bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4475 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4476 return false;
4477 }
4478
4479 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0
4480 && state.rawPointerData.pointerCount != 0;
4481 if (initialDown) {
4482 if (mExternalStylusState.pressure != 0.0f) {
4483#if DEBUG_STYLUS_FUSION
4484 ALOGD("Have both stylus and touch data, beginning fusion");
4485#endif
4486 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4487 } else if (timeout) {
4488#if DEBUG_STYLUS_FUSION
4489 ALOGD("Timeout expired, assuming touch is not a stylus.");
4490#endif
4491 resetExternalStylus();
4492 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004493 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4494 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004495 }
4496#if DEBUG_STYLUS_FUSION
4497 ALOGD("No stylus data but stylus is connected, requesting timeout "
Michael Wright43fd19f2015-04-21 19:02:58 +01004498 "(%" PRId64 "ms)", mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004499#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004500 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004501 return true;
4502 }
4503 }
4504
4505 // Check if the stylus pointer has gone up.
4506 if (mExternalStylusId != -1 &&
4507 !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
4508#if DEBUG_STYLUS_FUSION
4509 ALOGD("Stylus pointer is going up");
4510#endif
4511 mExternalStylusId = -1;
4512 }
4513
4514 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004515}
4516
4517void TouchInputMapper::timeoutExpired(nsecs_t when) {
4518 if (mDeviceMode == DEVICE_MODE_POINTER) {
4519 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4520 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4521 }
Michael Wright842500e2015-03-13 17:32:02 -07004522 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004523 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004524 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004525 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4526 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004527 }
4528 }
4529}
4530
4531void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004532 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004533 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004534 // We're either in the middle of a fused stream of data or we're waiting on data before
4535 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4536 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004537 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004538 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004539 }
4540}
4541
4542bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4543 // Check for release of a virtual key.
4544 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004545 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004546 // Pointer went up while virtual key was down.
4547 mCurrentVirtualKey.down = false;
4548 if (!mCurrentVirtualKey.ignored) {
4549#if DEBUG_VIRTUAL_KEYS
4550 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
4551 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4552#endif
4553 dispatchVirtualKey(when, policyFlags,
4554 AKEY_EVENT_ACTION_UP,
4555 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4556 }
4557 return true;
4558 }
4559
Michael Wright842500e2015-03-13 17:32:02 -07004560 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4561 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4562 const RawPointerData::Pointer& pointer =
4563 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004564 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4565 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4566 // Pointer is still within the space of the virtual key.
4567 return true;
4568 }
4569 }
4570
4571 // Pointer left virtual key area or another pointer also went down.
4572 // Send key cancellation but do not consume the touch yet.
4573 // This is useful when the user swipes through from the virtual key area
4574 // into the main display surface.
4575 mCurrentVirtualKey.down = false;
4576 if (!mCurrentVirtualKey.ignored) {
4577#if DEBUG_VIRTUAL_KEYS
4578 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
4579 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
4580#endif
4581 dispatchVirtualKey(when, policyFlags,
4582 AKEY_EVENT_ACTION_UP,
4583 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY
4584 | AKEY_EVENT_FLAG_CANCELED);
4585 }
4586 }
4587
Michael Wright842500e2015-03-13 17:32:02 -07004588 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty()
4589 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004590 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004591 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4592 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004593 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4594 // If exactly one pointer went down, check for virtual key hit.
4595 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004596 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4598 if (virtualKey) {
4599 mCurrentVirtualKey.down = true;
4600 mCurrentVirtualKey.downTime = when;
4601 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4602 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
4603 mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey(
4604 when, getDevice(), virtualKey->keyCode, virtualKey->scanCode);
4605
4606 if (!mCurrentVirtualKey.ignored) {
4607#if DEBUG_VIRTUAL_KEYS
4608 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
4609 mCurrentVirtualKey.keyCode,
4610 mCurrentVirtualKey.scanCode);
4611#endif
4612 dispatchVirtualKey(when, policyFlags,
4613 AKEY_EVENT_ACTION_DOWN,
4614 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
4615 }
4616 }
4617 }
4618 return true;
4619 }
4620 }
4621
4622 // Disable all virtual key touches that happen within a short time interval of the
4623 // most recent touch within the screen area. The idea is to filter out stray
4624 // virtual key presses when interacting with the touch screen.
4625 //
4626 // Problems we're trying to solve:
4627 //
4628 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4629 // virtual key area that is implemented by a separate touch panel and accidentally
4630 // triggers a virtual key.
4631 //
4632 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4633 // area and accidentally triggers a virtual key. This often happens when virtual keys
4634 // are layed out below the screen near to where the on screen keyboard's space bar
4635 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004636 if (mConfig.virtualKeyQuietTime > 0 &&
4637 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004638 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4639 }
4640 return false;
4641}
4642
4643void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
4644 int32_t keyEventAction, int32_t keyEventFlags) {
4645 int32_t keyCode = mCurrentVirtualKey.keyCode;
4646 int32_t scanCode = mCurrentVirtualKey.scanCode;
4647 nsecs_t downTime = mCurrentVirtualKey.downTime;
4648 int32_t metaState = mContext->getGlobalMetaState();
4649 policyFlags |= POLICY_FLAG_VIRTUAL;
4650
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01004651 NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
4652 policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004653 getListener()->notifyKey(&args);
4654}
4655
Michael Wright8e812822015-06-22 16:18:21 +01004656void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4657 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4658 if (!currentIdBits.isEmpty()) {
4659 int32_t metaState = getContext()->getGlobalMetaState();
4660 int32_t buttonState = mCurrentCookedState.buttonState;
4661 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
4662 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004663 mCurrentCookedState.deviceTimestamp,
Michael Wright8e812822015-06-22 16:18:21 +01004664 mCurrentCookedState.cookedPointerData.pointerProperties,
4665 mCurrentCookedState.cookedPointerData.pointerCoords,
4666 mCurrentCookedState.cookedPointerData.idToIndex,
4667 currentIdBits, -1,
4668 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4669 mCurrentMotionAborted = true;
4670 }
4671}
4672
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004674 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4675 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004676 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004677 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004678
4679 if (currentIdBits == lastIdBits) {
4680 if (!currentIdBits.isEmpty()) {
4681 // No pointer id changes so this is a move event.
4682 // The listener takes care of batching moves so we don't have to deal with that here.
4683 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004684 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004685 AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004686 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004687 mCurrentCookedState.cookedPointerData.pointerProperties,
4688 mCurrentCookedState.cookedPointerData.pointerCoords,
4689 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004690 currentIdBits, -1,
4691 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4692 }
4693 } else {
4694 // There may be pointers going up and pointers going down and pointers moving
4695 // all at the same time.
4696 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4697 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4698 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4699 BitSet32 dispatchedIdBits(lastIdBits.value);
4700
4701 // Update last coordinates of pointers that have moved so that we observe the new
4702 // pointer positions at the same time as other pointers that have just gone up.
4703 bool moveNeeded = updateMovedPointers(
Michael Wright842500e2015-03-13 17:32:02 -07004704 mCurrentCookedState.cookedPointerData.pointerProperties,
4705 mCurrentCookedState.cookedPointerData.pointerCoords,
4706 mCurrentCookedState.cookedPointerData.idToIndex,
4707 mLastCookedState.cookedPointerData.pointerProperties,
4708 mLastCookedState.cookedPointerData.pointerCoords,
4709 mLastCookedState.cookedPointerData.idToIndex,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004710 moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004711 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004712 moveNeeded = true;
4713 }
4714
4715 // Dispatch pointer up events.
4716 while (!upIdBits.isEmpty()) {
4717 uint32_t upId = upIdBits.clearFirstMarkedBit();
4718
4719 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004720 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004721 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004722 mLastCookedState.cookedPointerData.pointerProperties,
4723 mLastCookedState.cookedPointerData.pointerCoords,
4724 mLastCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004725 dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004726 dispatchedIdBits.clearBit(upId);
4727 }
4728
4729 // Dispatch move events if any of the remaining pointers moved from their old locations.
4730 // Although applications receive new locations as part of individual pointer up
4731 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004732 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004733 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
4734 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004735 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004736 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004737 mCurrentCookedState.cookedPointerData.pointerProperties,
4738 mCurrentCookedState.cookedPointerData.pointerCoords,
4739 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004740 dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004741 }
4742
4743 // Dispatch pointer down events using the new pointer locations.
4744 while (!downIdBits.isEmpty()) {
4745 uint32_t downId = downIdBits.clearFirstMarkedBit();
4746 dispatchedIdBits.markBit(downId);
4747
4748 if (dispatchedIdBits.count() == 1) {
4749 // First pointer is going down. Set down time.
4750 mDownTime = when;
4751 }
4752
4753 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004754 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004755 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004756 mCurrentCookedState.cookedPointerData.pointerProperties,
4757 mCurrentCookedState.cookedPointerData.pointerCoords,
4758 mCurrentCookedState.cookedPointerData.idToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01004759 dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004760 }
4761 }
4762}
4763
4764void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4765 if (mSentHoverEnter &&
Michael Wright842500e2015-03-13 17:32:02 -07004766 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()
4767 || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 int32_t metaState = getContext()->getGlobalMetaState();
4769 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004770 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004771 mLastCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004772 mLastCookedState.cookedPointerData.pointerProperties,
4773 mLastCookedState.cookedPointerData.pointerCoords,
4774 mLastCookedState.cookedPointerData.idToIndex,
4775 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004776 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4777 mSentHoverEnter = false;
4778 }
4779}
4780
4781void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004782 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty()
4783 && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004784 int32_t metaState = getContext()->getGlobalMetaState();
4785 if (!mSentHoverEnter) {
Michael Wright842500e2015-03-13 17:32:02 -07004786 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
Michael Wright7b159c92015-05-14 14:48:03 +01004787 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004788 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004789 mCurrentCookedState.cookedPointerData.pointerProperties,
4790 mCurrentCookedState.cookedPointerData.pointerCoords,
4791 mCurrentCookedState.cookedPointerData.idToIndex,
4792 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004793 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4794 mSentHoverEnter = true;
4795 }
4796
4797 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01004798 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07004799 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004800 mCurrentCookedState.deviceTimestamp,
Michael Wright842500e2015-03-13 17:32:02 -07004801 mCurrentCookedState.cookedPointerData.pointerProperties,
4802 mCurrentCookedState.cookedPointerData.pointerCoords,
4803 mCurrentCookedState.cookedPointerData.idToIndex,
4804 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
Michael Wrightd02c5b62014-02-10 15:10:22 -08004805 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4806 }
4807}
4808
Michael Wright7b159c92015-05-14 14:48:03 +01004809void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4810 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4811 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4812 const int32_t metaState = getContext()->getGlobalMetaState();
4813 int32_t buttonState = mLastCookedState.buttonState;
4814 while (!releasedButtons.isEmpty()) {
4815 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4816 buttonState &= ~actionButton;
4817 dispatchMotion(when, policyFlags, mSource,
4818 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton,
4819 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004820 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004821 mCurrentCookedState.cookedPointerData.pointerProperties,
4822 mCurrentCookedState.cookedPointerData.pointerCoords,
4823 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4824 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4825 }
4826}
4827
4828void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4829 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4830 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4831 const int32_t metaState = getContext()->getGlobalMetaState();
4832 int32_t buttonState = mLastCookedState.buttonState;
4833 while (!pressedButtons.isEmpty()) {
4834 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4835 buttonState |= actionButton;
4836 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
4837 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004838 mCurrentCookedState.deviceTimestamp,
Michael Wright7b159c92015-05-14 14:48:03 +01004839 mCurrentCookedState.cookedPointerData.pointerProperties,
4840 mCurrentCookedState.cookedPointerData.pointerCoords,
4841 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4842 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
4843 }
4844}
4845
4846const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4847 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4848 return cookedPointerData.touchingIdBits;
4849 }
4850 return cookedPointerData.hoveringIdBits;
4851}
4852
Michael Wrightd02c5b62014-02-10 15:10:22 -08004853void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004854 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004855
Michael Wright842500e2015-03-13 17:32:02 -07004856 mCurrentCookedState.cookedPointerData.clear();
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08004857 mCurrentCookedState.deviceTimestamp =
4858 mCurrentRawState.deviceTimestamp;
Michael Wright842500e2015-03-13 17:32:02 -07004859 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4860 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4861 mCurrentRawState.rawPointerData.hoveringIdBits;
4862 mCurrentCookedState.cookedPointerData.touchingIdBits =
4863 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004864
Michael Wright7b159c92015-05-14 14:48:03 +01004865 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4866 mCurrentCookedState.buttonState = 0;
4867 } else {
4868 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4869 }
4870
Michael Wrightd02c5b62014-02-10 15:10:22 -08004871 // Walk through the the active pointers and map device coordinates onto
4872 // surface coordinates and adjust for display orientation.
4873 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004874 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004875
4876 // Size
4877 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4878 switch (mCalibration.sizeCalibration) {
4879 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4880 case Calibration::SIZE_CALIBRATION_DIAMETER:
4881 case Calibration::SIZE_CALIBRATION_BOX:
4882 case Calibration::SIZE_CALIBRATION_AREA:
4883 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4884 touchMajor = in.touchMajor;
4885 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4886 toolMajor = in.toolMajor;
4887 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4888 size = mRawPointerAxes.touchMinor.valid
4889 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4890 } else if (mRawPointerAxes.touchMajor.valid) {
4891 toolMajor = touchMajor = in.touchMajor;
4892 toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid
4893 ? in.touchMinor : in.touchMajor;
4894 size = mRawPointerAxes.touchMinor.valid
4895 ? avg(in.touchMajor, in.touchMinor) : in.touchMajor;
4896 } else if (mRawPointerAxes.toolMajor.valid) {
4897 touchMajor = toolMajor = in.toolMajor;
4898 touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid
4899 ? in.toolMinor : in.toolMajor;
4900 size = mRawPointerAxes.toolMinor.valid
4901 ? avg(in.toolMajor, in.toolMinor) : in.toolMajor;
4902 } else {
4903 ALOG_ASSERT(false, "No touch or tool axes. "
4904 "Size calibration should have been resolved to NONE.");
4905 touchMajor = 0;
4906 touchMinor = 0;
4907 toolMajor = 0;
4908 toolMinor = 0;
4909 size = 0;
4910 }
4911
4912 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
Michael Wright842500e2015-03-13 17:32:02 -07004913 uint32_t touchingCount =
4914 mCurrentRawState.rawPointerData.touchingIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004915 if (touchingCount > 1) {
4916 touchMajor /= touchingCount;
4917 touchMinor /= touchingCount;
4918 toolMajor /= touchingCount;
4919 toolMinor /= touchingCount;
4920 size /= touchingCount;
4921 }
4922 }
4923
4924 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4925 touchMajor *= mGeometricScale;
4926 touchMinor *= mGeometricScale;
4927 toolMajor *= mGeometricScale;
4928 toolMinor *= mGeometricScale;
4929 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4930 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4931 touchMinor = touchMajor;
4932 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4933 toolMinor = toolMajor;
4934 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4935 touchMinor = touchMajor;
4936 toolMinor = toolMajor;
4937 }
4938
4939 mCalibration.applySizeScaleAndBias(&touchMajor);
4940 mCalibration.applySizeScaleAndBias(&touchMinor);
4941 mCalibration.applySizeScaleAndBias(&toolMajor);
4942 mCalibration.applySizeScaleAndBias(&toolMinor);
4943 size *= mSizeScale;
4944 break;
4945 default:
4946 touchMajor = 0;
4947 touchMinor = 0;
4948 toolMajor = 0;
4949 toolMinor = 0;
4950 size = 0;
4951 break;
4952 }
4953
4954 // Pressure
4955 float pressure;
4956 switch (mCalibration.pressureCalibration) {
4957 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4958 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4959 pressure = in.pressure * mPressureScale;
4960 break;
4961 default:
4962 pressure = in.isHovering ? 0 : 1;
4963 break;
4964 }
4965
4966 // Tilt and Orientation
4967 float tilt;
4968 float orientation;
4969 if (mHaveTilt) {
4970 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
4971 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
4972 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
4973 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
4974 } else {
4975 tilt = 0;
4976
4977 switch (mCalibration.orientationCalibration) {
4978 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4979 orientation = in.orientation * mOrientationScale;
4980 break;
4981 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
4982 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
4983 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
4984 if (c1 != 0 || c2 != 0) {
4985 orientation = atan2f(c1, c2) * 0.5f;
4986 float confidence = hypotf(c1, c2);
4987 float scale = 1.0f + confidence / 16.0f;
4988 touchMajor *= scale;
4989 touchMinor /= scale;
4990 toolMajor *= scale;
4991 toolMinor /= scale;
4992 } else {
4993 orientation = 0;
4994 }
4995 break;
4996 }
4997 default:
4998 orientation = 0;
4999 }
5000 }
5001
5002 // Distance
5003 float distance;
5004 switch (mCalibration.distanceCalibration) {
5005 case Calibration::DISTANCE_CALIBRATION_SCALED:
5006 distance = in.distance * mDistanceScale;
5007 break;
5008 default:
5009 distance = 0;
5010 }
5011
5012 // Coverage
5013 int32_t rawLeft, rawTop, rawRight, rawBottom;
5014 switch (mCalibration.coverageCalibration) {
5015 case Calibration::COVERAGE_CALIBRATION_BOX:
5016 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5017 rawRight = in.toolMinor & 0x0000ffff;
5018 rawBottom = in.toolMajor & 0x0000ffff;
5019 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5020 break;
5021 default:
5022 rawLeft = rawTop = rawRight = rawBottom = 0;
5023 break;
5024 }
5025
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005026 // Adjust X,Y coords for device calibration
5027 // TODO: Adjust coverage coords?
5028 float xTransformed = in.x, yTransformed = in.y;
5029 mAffineTransform.applyTo(xTransformed, yTransformed);
5030
5031 // Adjust X, Y, and coverage coords for surface orientation.
5032 float x, y;
5033 float left, top, right, bottom;
5034
Michael Wrightd02c5b62014-02-10 15:10:22 -08005035 switch (mSurfaceOrientation) {
5036 case DISPLAY_ORIENTATION_90:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005037 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5038 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005039 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5040 right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5041 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5042 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5043 orientation -= M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005044 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005045 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5046 }
5047 break;
5048 case DISPLAY_ORIENTATION_180:
Michael Wright358bcc72018-08-21 04:01:07 +01005049 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005050 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005051 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5052 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005053 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5054 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5055 orientation -= M_PI;
baik.han18a81482015-04-14 19:49:28 +09005056 if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005057 orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5058 }
5059 break;
5060 case DISPLAY_ORIENTATION_270:
Michael Wright358bcc72018-08-21 04:01:07 +01005061 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005062 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
Michael Wright358bcc72018-08-21 04:01:07 +01005063 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5064 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005065 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5066 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5067 orientation += M_PI_2;
baik.han18a81482015-04-14 19:49:28 +09005068 if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005069 orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5070 }
5071 break;
5072 default:
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005073 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5074 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005075 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5076 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5077 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5078 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5079 break;
5080 }
5081
5082 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005083 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005084 out.clear();
5085 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5086 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5087 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5088 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5089 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5090 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5091 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5092 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5093 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5094 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5095 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5096 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5097 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5098 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5099 } else {
5100 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5101 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5102 }
5103
5104 // Write output properties.
Michael Wright842500e2015-03-13 17:32:02 -07005105 PointerProperties& properties =
5106 mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005107 uint32_t id = in.id;
5108 properties.clear();
5109 properties.id = id;
5110 properties.toolType = in.toolType;
5111
5112 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005113 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005114 }
5115}
5116
5117void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
5118 PointerUsage pointerUsage) {
5119 if (pointerUsage != mPointerUsage) {
5120 abortPointerUsage(when, policyFlags);
5121 mPointerUsage = pointerUsage;
5122 }
5123
5124 switch (mPointerUsage) {
5125 case POINTER_USAGE_GESTURES:
5126 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5127 break;
5128 case POINTER_USAGE_STYLUS:
5129 dispatchPointerStylus(when, policyFlags);
5130 break;
5131 case POINTER_USAGE_MOUSE:
5132 dispatchPointerMouse(when, policyFlags);
5133 break;
5134 default:
5135 break;
5136 }
5137}
5138
5139void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5140 switch (mPointerUsage) {
5141 case POINTER_USAGE_GESTURES:
5142 abortPointerGestures(when, policyFlags);
5143 break;
5144 case POINTER_USAGE_STYLUS:
5145 abortPointerStylus(when, policyFlags);
5146 break;
5147 case POINTER_USAGE_MOUSE:
5148 abortPointerMouse(when, policyFlags);
5149 break;
5150 default:
5151 break;
5152 }
5153
5154 mPointerUsage = POINTER_USAGE_NONE;
5155}
5156
5157void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags,
5158 bool isTimeout) {
5159 // Update current gesture coordinates.
5160 bool cancelPreviousGesture, finishPreviousGesture;
5161 bool sendEvents = preparePointerGestures(when,
5162 &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
5163 if (!sendEvents) {
5164 return;
5165 }
5166 if (finishPreviousGesture) {
5167 cancelPreviousGesture = false;
5168 }
5169
5170 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005171 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5172 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005173 if (finishPreviousGesture || cancelPreviousGesture) {
5174 mPointerController->clearSpots();
5175 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005176
5177 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5178 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
5179 mPointerGesture.currentGestureIdToIndex,
5180 mPointerGesture.currentGestureIdBits);
5181 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005182 } else {
5183 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5184 }
5185
5186 // Show or hide the pointer if needed.
5187 switch (mPointerGesture.currentGestureMode) {
5188 case PointerGesture::NEUTRAL:
5189 case PointerGesture::QUIET:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005190 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH
5191 && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005192 // Remind the user of where the pointer is after finishing a gesture with spots.
5193 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5194 }
5195 break;
5196 case PointerGesture::TAP:
5197 case PointerGesture::TAP_DRAG:
5198 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5199 case PointerGesture::HOVER:
5200 case PointerGesture::PRESS:
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005201 case PointerGesture::SWIPE:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005202 // Unfade the pointer when the current gesture manipulates the
5203 // area directly under the pointer.
5204 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5205 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005206 case PointerGesture::FREEFORM:
5207 // Fade the pointer when the current gesture manipulates a different
5208 // area and there are spots to guide the user experience.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005209 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005210 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5211 } else {
5212 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5213 }
5214 break;
5215 }
5216
5217 // Send events!
5218 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005219 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005220
5221 // Update last coordinates of pointers that have moved so that we observe the new
5222 // pointer positions at the same time as other pointers that have just gone up.
5223 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP
5224 || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG
5225 || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5226 || mPointerGesture.currentGestureMode == PointerGesture::PRESS
5227 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE
5228 || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
5229 bool moveNeeded = false;
5230 if (down && !cancelPreviousGesture && !finishPreviousGesture
5231 && !mPointerGesture.lastGestureIdBits.isEmpty()
5232 && !mPointerGesture.currentGestureIdBits.isEmpty()) {
5233 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value
5234 & mPointerGesture.lastGestureIdBits.value);
5235 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
5236 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5237 mPointerGesture.lastGestureProperties,
5238 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5239 movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005240 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005241 moveNeeded = true;
5242 }
5243 }
5244
5245 // Send motion events for all pointers that went up or were canceled.
5246 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5247 if (!dispatchedGestureIdBits.isEmpty()) {
5248 if (cancelPreviousGesture) {
5249 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005250 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005251 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005252 mPointerGesture.lastGestureProperties,
5253 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
Michael Wright7b159c92015-05-14 14:48:03 +01005254 dispatchedGestureIdBits, -1, 0,
5255 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005256
5257 dispatchedGestureIdBits.clear();
5258 } else {
5259 BitSet32 upGestureIdBits;
5260 if (finishPreviousGesture) {
5261 upGestureIdBits = dispatchedGestureIdBits;
5262 } else {
5263 upGestureIdBits.value = dispatchedGestureIdBits.value
5264 & ~mPointerGesture.currentGestureIdBits.value;
5265 }
5266 while (!upGestureIdBits.isEmpty()) {
5267 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5268
5269 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005270 AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005272 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005273 mPointerGesture.lastGestureProperties,
5274 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5275 dispatchedGestureIdBits, id,
5276 0, 0, mPointerGesture.downTime);
5277
5278 dispatchedGestureIdBits.clearBit(id);
5279 }
5280 }
5281 }
5282
5283 // Send motion events for all pointers that moved.
5284 if (moveNeeded) {
5285 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005286 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005287 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005288 mPointerGesture.currentGestureProperties,
5289 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5290 dispatchedGestureIdBits, -1,
5291 0, 0, mPointerGesture.downTime);
5292 }
5293
5294 // Send motion events for all pointers that went down.
5295 if (down) {
5296 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value
5297 & ~dispatchedGestureIdBits.value);
5298 while (!downGestureIdBits.isEmpty()) {
5299 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5300 dispatchedGestureIdBits.markBit(id);
5301
5302 if (dispatchedGestureIdBits.count() == 1) {
5303 mPointerGesture.downTime = when;
5304 }
5305
5306 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005307 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005308 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 mPointerGesture.currentGestureProperties,
5310 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5311 dispatchedGestureIdBits, id,
5312 0, 0, mPointerGesture.downTime);
5313 }
5314 }
5315
5316 // Send motion events for hover.
5317 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
5318 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005319 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005320 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005321 mPointerGesture.currentGestureProperties,
5322 mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex,
5323 mPointerGesture.currentGestureIdBits, -1,
5324 0, 0, mPointerGesture.downTime);
5325 } else if (dispatchedGestureIdBits.isEmpty()
5326 && !mPointerGesture.lastGestureIdBits.isEmpty()) {
5327 // Synthesize a hover move event after all pointers go up to indicate that
5328 // the pointer is hovering again even if the user is not currently touching
5329 // the touch pad. This ensures that a view will receive a fresh hover enter
5330 // event after a tap.
5331 float x, y;
5332 mPointerController->getPosition(&x, &y);
5333
5334 PointerProperties pointerProperties;
5335 pointerProperties.clear();
5336 pointerProperties.id = 0;
5337 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5338
5339 PointerCoords pointerCoords;
5340 pointerCoords.clear();
5341 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5342 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5343
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005344 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01005345 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005346 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08005347 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005348 0, 0, mPointerGesture.downTime);
5349 getListener()->notifyMotion(&args);
5350 }
5351
5352 // Update state.
5353 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5354 if (!down) {
5355 mPointerGesture.lastGestureIdBits.clear();
5356 } else {
5357 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
5358 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) {
5359 uint32_t id = idBits.clearFirstMarkedBit();
5360 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5361 mPointerGesture.lastGestureProperties[index].copyFrom(
5362 mPointerGesture.currentGestureProperties[index]);
5363 mPointerGesture.lastGestureCoords[index].copyFrom(
5364 mPointerGesture.currentGestureCoords[index]);
5365 mPointerGesture.lastGestureIdToIndex[id] = index;
5366 }
5367 }
5368}
5369
5370void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5371 // Cancel previously dispatches pointers.
5372 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5373 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005374 int32_t buttonState = mCurrentRawState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005375 dispatchMotion(when, policyFlags, mSource,
Michael Wright7b159c92015-05-14 14:48:03 +01005376 AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08005377 AMOTION_EVENT_EDGE_FLAG_NONE, /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08005378 mPointerGesture.lastGestureProperties,
5379 mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex,
5380 mPointerGesture.lastGestureIdBits, -1,
5381 0, 0, mPointerGesture.downTime);
5382 }
5383
5384 // Reset the current pointer gesture.
5385 mPointerGesture.reset();
5386 mPointerVelocityControl.reset();
5387
5388 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005389 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005390 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5391 mPointerController->clearSpots();
5392 }
5393}
5394
5395bool TouchInputMapper::preparePointerGestures(nsecs_t when,
5396 bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) {
5397 *outCancelPreviousGesture = false;
5398 *outFinishPreviousGesture = false;
5399
5400 // Handle TAP timeout.
5401 if (isTimeout) {
5402#if DEBUG_GESTURES
5403 ALOGD("Gestures: Processing timeout");
5404#endif
5405
5406 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5407 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5408 // The tap/drag timeout has not yet expired.
5409 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime
5410 + mConfig.pointerGestureTapDragInterval);
5411 } else {
5412 // The tap is finished.
5413#if DEBUG_GESTURES
5414 ALOGD("Gestures: TAP finished");
5415#endif
5416 *outFinishPreviousGesture = true;
5417
5418 mPointerGesture.activeGestureId = -1;
5419 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5420 mPointerGesture.currentGestureIdBits.clear();
5421
5422 mPointerVelocityControl.reset();
5423 return true;
5424 }
5425 }
5426
5427 // We did not handle this timeout.
5428 return false;
5429 }
5430
Michael Wright842500e2015-03-13 17:32:02 -07005431 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5432 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005433
5434 // Update the velocity tracker.
5435 {
5436 VelocityTracker::Position positions[MAX_POINTERS];
5437 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005438 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005439 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005440 const RawPointerData::Pointer& pointer =
5441 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005442 positions[count].x = pointer.x * mPointerXMovementScale;
5443 positions[count].y = pointer.y * mPointerYMovementScale;
5444 }
5445 mPointerGesture.velocityTracker.addMovement(when,
Michael Wright842500e2015-03-13 17:32:02 -07005446 mCurrentCookedState.fingerIdBits, positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005447 }
5448
5449 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5450 // to NEUTRAL, then we should not generate tap event.
5451 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER
5452 && mPointerGesture.lastGestureMode != PointerGesture::TAP
5453 && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
5454 mPointerGesture.resetTap();
5455 }
5456
5457 // Pick a new active touch id if needed.
5458 // Choose an arbitrary pointer that just went down, if there is one.
5459 // Otherwise choose an arbitrary remaining pointer.
5460 // This guarantees we always have an active touch id when there is at least one pointer.
5461 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005462 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5463 int32_t activeTouchId = lastActiveTouchId;
5464 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005465 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005466 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005467 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005468 mPointerGesture.firstTouchTime = when;
5469 }
Michael Wright842500e2015-03-13 17:32:02 -07005470 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005471 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005472 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005473 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005474 } else {
5475 activeTouchId = mPointerGesture.activeTouchId = -1;
5476 }
5477 }
5478
5479 // Determine whether we are in quiet time.
5480 bool isQuietTime = false;
5481 if (activeTouchId < 0) {
5482 mPointerGesture.resetQuietTime();
5483 } else {
5484 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5485 if (!isQuietTime) {
5486 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS
5487 || mPointerGesture.lastGestureMode == PointerGesture::SWIPE
5488 || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM)
5489 && currentFingerCount < 2) {
5490 // Enter quiet time when exiting swipe or freeform state.
5491 // This is to prevent accidentally entering the hover state and flinging the
5492 // pointer when finishing a swipe and there is still one pointer left onscreen.
5493 isQuietTime = true;
5494 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG
5495 && currentFingerCount >= 2
Michael Wright842500e2015-03-13 17:32:02 -07005496 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 // Enter quiet time when releasing the button and there are still two or more
5498 // fingers down. This may indicate that one finger was used to press the button
5499 // but it has not gone up yet.
5500 isQuietTime = true;
5501 }
5502 if (isQuietTime) {
5503 mPointerGesture.quietTime = when;
5504 }
5505 }
5506 }
5507
5508 // Switch states based on button and pointer state.
5509 if (isQuietTime) {
5510 // Case 1: Quiet time. (QUIET)
5511#if DEBUG_GESTURES
5512 ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime
5513 + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
5514#endif
5515 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5516 *outFinishPreviousGesture = true;
5517 }
5518
5519 mPointerGesture.activeGestureId = -1;
5520 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5521 mPointerGesture.currentGestureIdBits.clear();
5522
5523 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005524 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005525 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5526 // The pointer follows the active touch point.
5527 // Emit DOWN, MOVE, UP events at the pointer location.
5528 //
5529 // Only the active touch matters; other fingers are ignored. This policy helps
5530 // to handle the case where the user places a second finger on the touch pad
5531 // to apply the necessary force to depress an integrated button below the surface.
5532 // We don't want the second finger to be delivered to applications.
5533 //
5534 // For this to work well, we need to make sure to track the pointer that is really
5535 // active. If the user first puts one finger down to click then adds another
5536 // finger to drag then the active pointer should switch to the finger that is
5537 // being dragged.
5538#if DEBUG_GESTURES
5539 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
5540 "currentFingerCount=%d", activeTouchId, currentFingerCount);
5541#endif
5542 // Reset state when just starting.
5543 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5544 *outFinishPreviousGesture = true;
5545 mPointerGesture.activeGestureId = 0;
5546 }
5547
5548 // Switch pointers if needed.
5549 // Find the fastest pointer and follow it.
5550 if (activeTouchId >= 0 && currentFingerCount > 1) {
5551 int32_t bestId = -1;
5552 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Michael Wright842500e2015-03-13 17:32:02 -07005553 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 uint32_t id = idBits.clearFirstMarkedBit();
5555 float vx, vy;
5556 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5557 float speed = hypotf(vx, vy);
5558 if (speed > bestSpeed) {
5559 bestId = id;
5560 bestSpeed = speed;
5561 }
5562 }
5563 }
5564 if (bestId >= 0 && bestId != activeTouchId) {
5565 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005566#if DEBUG_GESTURES
5567 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
5568 "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed);
5569#endif
5570 }
5571 }
5572
Jun Mukaifa1706a2015-12-03 01:14:46 -08005573 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005574 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005575 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005576 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005577 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005578 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005579 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5580 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005581
5582 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5583 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5584
5585 // Move the pointer using a relative motion.
5586 // When using spots, the click will occur at the position of the anchor
5587 // spot and all other spots will move there.
5588 mPointerController->move(deltaX, deltaY);
5589 } else {
5590 mPointerVelocityControl.reset();
5591 }
5592
5593 float x, y;
5594 mPointerController->getPosition(&x, &y);
5595
5596 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5597 mPointerGesture.currentGestureIdBits.clear();
5598 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5599 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5600 mPointerGesture.currentGestureProperties[0].clear();
5601 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5602 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5603 mPointerGesture.currentGestureCoords[0].clear();
5604 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5605 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5606 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5607 } else if (currentFingerCount == 0) {
5608 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5609 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5610 *outFinishPreviousGesture = true;
5611 }
5612
5613 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5614 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5615 bool tapped = false;
5616 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER
5617 || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG)
5618 && lastFingerCount == 1) {
5619 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5620 float x, y;
5621 mPointerController->getPosition(&x, &y);
5622 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5623 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5624#if DEBUG_GESTURES
5625 ALOGD("Gestures: TAP");
5626#endif
5627
5628 mPointerGesture.tapUpTime = when;
5629 getContext()->requestTimeoutAtTime(when
5630 + mConfig.pointerGestureTapDragInterval);
5631
5632 mPointerGesture.activeGestureId = 0;
5633 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5634 mPointerGesture.currentGestureIdBits.clear();
5635 mPointerGesture.currentGestureIdBits.markBit(
5636 mPointerGesture.activeGestureId);
5637 mPointerGesture.currentGestureIdToIndex[
5638 mPointerGesture.activeGestureId] = 0;
5639 mPointerGesture.currentGestureProperties[0].clear();
5640 mPointerGesture.currentGestureProperties[0].id =
5641 mPointerGesture.activeGestureId;
5642 mPointerGesture.currentGestureProperties[0].toolType =
5643 AMOTION_EVENT_TOOL_TYPE_FINGER;
5644 mPointerGesture.currentGestureCoords[0].clear();
5645 mPointerGesture.currentGestureCoords[0].setAxisValue(
5646 AMOTION_EVENT_AXIS_X, mPointerGesture.tapX);
5647 mPointerGesture.currentGestureCoords[0].setAxisValue(
5648 AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY);
5649 mPointerGesture.currentGestureCoords[0].setAxisValue(
5650 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5651
5652 tapped = true;
5653 } else {
5654#if DEBUG_GESTURES
5655 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f",
5656 x - mPointerGesture.tapX,
5657 y - mPointerGesture.tapY);
5658#endif
5659 }
5660 } else {
5661#if DEBUG_GESTURES
5662 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5663 ALOGD("Gestures: Not a TAP, %0.3fms since down",
5664 (when - mPointerGesture.tapDownTime) * 0.000001f);
5665 } else {
5666 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5667 }
5668#endif
5669 }
5670 }
5671
5672 mPointerVelocityControl.reset();
5673
5674 if (!tapped) {
5675#if DEBUG_GESTURES
5676 ALOGD("Gestures: NEUTRAL");
5677#endif
5678 mPointerGesture.activeGestureId = -1;
5679 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5680 mPointerGesture.currentGestureIdBits.clear();
5681 }
5682 } else if (currentFingerCount == 1) {
5683 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5684 // The pointer follows the active touch point.
5685 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5686 // When in TAP_DRAG, emit MOVE events at the pointer location.
5687 ALOG_ASSERT(activeTouchId >= 0);
5688
5689 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5690 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5691 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5692 float x, y;
5693 mPointerController->getPosition(&x, &y);
5694 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop
5695 && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
5696 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5697 } else {
5698#if DEBUG_GESTURES
5699 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
5700 x - mPointerGesture.tapX,
5701 y - mPointerGesture.tapY);
5702#endif
5703 }
5704 } else {
5705#if DEBUG_GESTURES
5706 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
5707 (when - mPointerGesture.tapUpTime) * 0.000001f);
5708#endif
5709 }
5710 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5711 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5712 }
5713
Jun Mukaifa1706a2015-12-03 01:14:46 -08005714 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005715 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005716 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005717 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005718 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005719 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005720 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5721 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005722
5723 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5724 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5725
5726 // Move the pointer using a relative motion.
5727 // When using spots, the hover or drag will occur at the position of the anchor spot.
5728 mPointerController->move(deltaX, deltaY);
5729 } else {
5730 mPointerVelocityControl.reset();
5731 }
5732
5733 bool down;
5734 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5735#if DEBUG_GESTURES
5736 ALOGD("Gestures: TAP_DRAG");
5737#endif
5738 down = true;
5739 } else {
5740#if DEBUG_GESTURES
5741 ALOGD("Gestures: HOVER");
5742#endif
5743 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5744 *outFinishPreviousGesture = true;
5745 }
5746 mPointerGesture.activeGestureId = 0;
5747 down = false;
5748 }
5749
5750 float x, y;
5751 mPointerController->getPosition(&x, &y);
5752
5753 mPointerGesture.currentGestureIdBits.clear();
5754 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5755 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5756 mPointerGesture.currentGestureProperties[0].clear();
5757 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5758 mPointerGesture.currentGestureProperties[0].toolType =
5759 AMOTION_EVENT_TOOL_TYPE_FINGER;
5760 mPointerGesture.currentGestureCoords[0].clear();
5761 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5762 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5763 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
5764 down ? 1.0f : 0.0f);
5765
5766 if (lastFingerCount == 0 && currentFingerCount != 0) {
5767 mPointerGesture.resetTap();
5768 mPointerGesture.tapDownTime = when;
5769 mPointerGesture.tapX = x;
5770 mPointerGesture.tapY = y;
5771 }
5772 } else {
5773 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5774 // We need to provide feedback for each finger that goes down so we cannot wait
5775 // for the fingers to move before deciding what to do.
5776 //
5777 // The ambiguous case is deciding what to do when there are two fingers down but they
5778 // have not moved enough to determine whether they are part of a drag or part of a
5779 // freeform gesture, or just a press or long-press at the pointer location.
5780 //
5781 // When there are two fingers we start with the PRESS hypothesis and we generate a
5782 // down at the pointer location.
5783 //
5784 // When the two fingers move enough or when additional fingers are added, we make
5785 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5786 ALOG_ASSERT(activeTouchId >= 0);
5787
5788 bool settled = when >= mPointerGesture.firstTouchTime
5789 + mConfig.pointerGestureMultitouchSettleInterval;
5790 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS
5791 && mPointerGesture.lastGestureMode != PointerGesture::SWIPE
5792 && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
5793 *outFinishPreviousGesture = true;
5794 } else if (!settled && currentFingerCount > lastFingerCount) {
5795 // Additional pointers have gone down but not yet settled.
5796 // Reset the gesture.
5797#if DEBUG_GESTURES
5798 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
5799 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5800 + mConfig.pointerGestureMultitouchSettleInterval - when)
5801 * 0.000001f);
5802#endif
5803 *outCancelPreviousGesture = true;
5804 } else {
5805 // Continue previous gesture.
5806 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5807 }
5808
5809 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5810 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5811 mPointerGesture.activeGestureId = 0;
5812 mPointerGesture.referenceIdBits.clear();
5813 mPointerVelocityControl.reset();
5814
5815 // Use the centroid and pointer location as the reference points for the gesture.
5816#if DEBUG_GESTURES
5817 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
5818 "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime
5819 + mConfig.pointerGestureMultitouchSettleInterval - when)
5820 * 0.000001f);
5821#endif
Michael Wright842500e2015-03-13 17:32:02 -07005822 mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers(
Michael Wrightd02c5b62014-02-10 15:10:22 -08005823 &mPointerGesture.referenceTouchX,
5824 &mPointerGesture.referenceTouchY);
5825 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
5826 &mPointerGesture.referenceGestureY);
5827 }
5828
5829 // Clear the reference deltas for fingers not yet included in the reference calculation.
Michael Wright842500e2015-03-13 17:32:02 -07005830 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value
Michael Wrightd02c5b62014-02-10 15:10:22 -08005831 & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) {
5832 uint32_t id = idBits.clearFirstMarkedBit();
5833 mPointerGesture.referenceDeltas[id].dx = 0;
5834 mPointerGesture.referenceDeltas[id].dy = 0;
5835 }
Michael Wright842500e2015-03-13 17:32:02 -07005836 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005837
5838 // Add delta for all fingers and calculate a common movement delta.
5839 float commonDeltaX = 0, commonDeltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005840 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value
5841 & mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005842 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) {
5843 bool first = (idBits == commonIdBits);
5844 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005845 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5846 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5848 delta.dx += cpd.x - lpd.x;
5849 delta.dy += cpd.y - lpd.y;
5850
5851 if (first) {
5852 commonDeltaX = delta.dx;
5853 commonDeltaY = delta.dy;
5854 } else {
5855 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5856 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5857 }
5858 }
5859
5860 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5861 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5862 float dist[MAX_POINTER_ID + 1];
5863 int32_t distOverThreshold = 0;
5864 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5865 uint32_t id = idBits.clearFirstMarkedBit();
5866 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5867 dist[id] = hypotf(delta.dx * mPointerXZoomScale,
5868 delta.dy * mPointerYZoomScale);
5869 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5870 distOverThreshold += 1;
5871 }
5872 }
5873
5874 // Only transition when at least two pointers have moved further than
5875 // the minimum distance threshold.
5876 if (distOverThreshold >= 2) {
5877 if (currentFingerCount > 2) {
5878 // There are more than two pointers, switch to FREEFORM.
5879#if DEBUG_GESTURES
5880 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
5881 currentFingerCount);
5882#endif
5883 *outCancelPreviousGesture = true;
5884 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5885 } else {
5886 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005887 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005888 uint32_t id1 = idBits.clearFirstMarkedBit();
5889 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005890 const RawPointerData::Pointer& p1 =
5891 mCurrentRawState.rawPointerData.pointerForId(id1);
5892 const RawPointerData::Pointer& p2 =
5893 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005894 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5895 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5896 // There are two pointers but they are too far apart for a SWIPE,
5897 // switch to FREEFORM.
5898#if DEBUG_GESTURES
5899 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
5900 mutualDistance, mPointerGestureMaxSwipeWidth);
5901#endif
5902 *outCancelPreviousGesture = true;
5903 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5904 } else {
5905 // There are two pointers. Wait for both pointers to start moving
5906 // before deciding whether this is a SWIPE or FREEFORM gesture.
5907 float dist1 = dist[id1];
5908 float dist2 = dist[id2];
5909 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance
5910 && dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
5911 // Calculate the dot product of the displacement vectors.
5912 // When the vectors are oriented in approximately the same direction,
5913 // the angle betweeen them is near zero and the cosine of the angle
5914 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2).
5915 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5916 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5917 float dx1 = delta1.dx * mPointerXZoomScale;
5918 float dy1 = delta1.dy * mPointerYZoomScale;
5919 float dx2 = delta2.dx * mPointerXZoomScale;
5920 float dy2 = delta2.dy * mPointerYZoomScale;
5921 float dot = dx1 * dx2 + dy1 * dy2;
5922 float cosine = dot / (dist1 * dist2); // denominator always > 0
5923 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5924 // Pointers are moving in the same direction. Switch to SWIPE.
5925#if DEBUG_GESTURES
5926 ALOGD("Gestures: PRESS transitioned to SWIPE, "
5927 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5928 "cosine %0.3f >= %0.3f",
5929 dist1, mConfig.pointerGestureMultitouchMinDistance,
5930 dist2, mConfig.pointerGestureMultitouchMinDistance,
5931 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5932#endif
5933 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5934 } else {
5935 // Pointers are moving in different directions. Switch to FREEFORM.
5936#if DEBUG_GESTURES
5937 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
5938 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5939 "cosine %0.3f < %0.3f",
5940 dist1, mConfig.pointerGestureMultitouchMinDistance,
5941 dist2, mConfig.pointerGestureMultitouchMinDistance,
5942 cosine, mConfig.pointerGestureSwipeTransitionAngleCosine);
5943#endif
5944 *outCancelPreviousGesture = true;
5945 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5946 }
5947 }
5948 }
5949 }
5950 }
5951 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5952 // Switch from SWIPE to FREEFORM if additional pointers go down.
5953 // Cancel previous gesture.
5954 if (currentFingerCount > 2) {
5955#if DEBUG_GESTURES
5956 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
5957 currentFingerCount);
5958#endif
5959 *outCancelPreviousGesture = true;
5960 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5961 }
5962 }
5963
5964 // Move the reference points based on the overall group motion of the fingers
5965 // except in PRESS mode while waiting for a transition to occur.
5966 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS
5967 && (commonDeltaX || commonDeltaY)) {
5968 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) {
5969 uint32_t id = idBits.clearFirstMarkedBit();
5970 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5971 delta.dx = 0;
5972 delta.dy = 0;
5973 }
5974
5975 mPointerGesture.referenceTouchX += commonDeltaX;
5976 mPointerGesture.referenceTouchY += commonDeltaY;
5977
5978 commonDeltaX *= mPointerXMovementScale;
5979 commonDeltaY *= mPointerYMovementScale;
5980
5981 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
5982 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
5983
5984 mPointerGesture.referenceGestureX += commonDeltaX;
5985 mPointerGesture.referenceGestureY += commonDeltaY;
5986 }
5987
5988 // Report gestures.
5989 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS
5990 || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
5991 // PRESS or SWIPE mode.
5992#if DEBUG_GESTURES
5993 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
5994 "activeGestureId=%d, currentTouchPointerCount=%d",
5995 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
5996#endif
5997 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
5998
5999 mPointerGesture.currentGestureIdBits.clear();
6000 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6001 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6002 mPointerGesture.currentGestureProperties[0].clear();
6003 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
6004 mPointerGesture.currentGestureProperties[0].toolType =
6005 AMOTION_EVENT_TOOL_TYPE_FINGER;
6006 mPointerGesture.currentGestureCoords[0].clear();
6007 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
6008 mPointerGesture.referenceGestureX);
6009 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
6010 mPointerGesture.referenceGestureY);
6011 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6012 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6013 // FREEFORM mode.
6014#if DEBUG_GESTURES
6015 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
6016 "activeGestureId=%d, currentTouchPointerCount=%d",
6017 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
6018#endif
6019 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6020
6021 mPointerGesture.currentGestureIdBits.clear();
6022
6023 BitSet32 mappedTouchIdBits;
6024 BitSet32 usedGestureIdBits;
6025 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6026 // Initially, assign the active gesture id to the active touch point
6027 // if there is one. No other touch id bits are mapped yet.
6028 if (!*outCancelPreviousGesture) {
6029 mappedTouchIdBits.markBit(activeTouchId);
6030 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6031 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6032 mPointerGesture.activeGestureId;
6033 } else {
6034 mPointerGesture.activeGestureId = -1;
6035 }
6036 } else {
6037 // Otherwise, assume we mapped all touches from the previous frame.
6038 // Reuse all mappings that are still applicable.
Michael Wright842500e2015-03-13 17:32:02 -07006039 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value
6040 & mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006041 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6042
6043 // Check whether we need to choose a new active gesture id because the
6044 // current went went up.
Michael Wright842500e2015-03-13 17:32:02 -07006045 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value
6046 & ~mCurrentCookedState.fingerIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006047 !upTouchIdBits.isEmpty(); ) {
6048 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6049 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6050 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6051 mPointerGesture.activeGestureId = -1;
6052 break;
6053 }
6054 }
6055 }
6056
6057#if DEBUG_GESTURES
6058 ALOGD("Gestures: FREEFORM follow up "
6059 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6060 "activeGestureId=%d",
6061 mappedTouchIdBits.value, usedGestureIdBits.value,
6062 mPointerGesture.activeGestureId);
6063#endif
6064
Michael Wright842500e2015-03-13 17:32:02 -07006065 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006066 for (uint32_t i = 0; i < currentFingerCount; i++) {
6067 uint32_t touchId = idBits.clearFirstMarkedBit();
6068 uint32_t gestureId;
6069 if (!mappedTouchIdBits.hasBit(touchId)) {
6070 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6071 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6072#if DEBUG_GESTURES
6073 ALOGD("Gestures: FREEFORM "
6074 "new mapping for touch id %d -> gesture id %d",
6075 touchId, gestureId);
6076#endif
6077 } else {
6078 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6079#if DEBUG_GESTURES
6080 ALOGD("Gestures: FREEFORM "
6081 "existing mapping for touch id %d -> gesture id %d",
6082 touchId, gestureId);
6083#endif
6084 }
6085 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6086 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6087
6088 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006089 mCurrentRawState.rawPointerData.pointerForId(touchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006090 float deltaX = (pointer.x - mPointerGesture.referenceTouchX)
6091 * mPointerXZoomScale;
6092 float deltaY = (pointer.y - mPointerGesture.referenceTouchY)
6093 * mPointerYZoomScale;
6094 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6095
6096 mPointerGesture.currentGestureProperties[i].clear();
6097 mPointerGesture.currentGestureProperties[i].id = gestureId;
6098 mPointerGesture.currentGestureProperties[i].toolType =
6099 AMOTION_EVENT_TOOL_TYPE_FINGER;
6100 mPointerGesture.currentGestureCoords[i].clear();
6101 mPointerGesture.currentGestureCoords[i].setAxisValue(
6102 AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX);
6103 mPointerGesture.currentGestureCoords[i].setAxisValue(
6104 AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY);
6105 mPointerGesture.currentGestureCoords[i].setAxisValue(
6106 AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6107 }
6108
6109 if (mPointerGesture.activeGestureId < 0) {
6110 mPointerGesture.activeGestureId =
6111 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6112#if DEBUG_GESTURES
6113 ALOGD("Gestures: FREEFORM new "
6114 "activeGestureId=%d", mPointerGesture.activeGestureId);
6115#endif
6116 }
6117 }
6118 }
6119
Michael Wright842500e2015-03-13 17:32:02 -07006120 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006121
6122#if DEBUG_GESTURES
6123 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
6124 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6125 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6126 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6127 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6128 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6129 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) {
6130 uint32_t id = idBits.clearFirstMarkedBit();
6131 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6132 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6133 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6134 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
6135 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6136 id, index, properties.toolType,
6137 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6138 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6139 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6140 }
6141 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) {
6142 uint32_t id = idBits.clearFirstMarkedBit();
6143 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6144 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6145 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6146 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
6147 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6148 id, index, properties.toolType,
6149 coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6150 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6151 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
6152 }
6153#endif
6154 return true;
6155}
6156
6157void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6158 mPointerSimple.currentCoords.clear();
6159 mPointerSimple.currentProperties.clear();
6160
6161 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006162 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6163 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6164 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6165 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6166 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006167 mPointerController->setPosition(x, y);
6168
Michael Wright842500e2015-03-13 17:32:02 -07006169 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170 down = !hovering;
6171
6172 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006173 mPointerSimple.currentCoords.copyFrom(
6174 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006175 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6176 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6177 mPointerSimple.currentProperties.id = 0;
6178 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006179 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006180 } else {
6181 down = false;
6182 hovering = false;
6183 }
6184
6185 dispatchPointerSimple(when, policyFlags, down, hovering);
6186}
6187
6188void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6189 abortPointerSimple(when, policyFlags);
6190}
6191
6192void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6193 mPointerSimple.currentCoords.clear();
6194 mPointerSimple.currentProperties.clear();
6195
6196 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006197 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6198 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6199 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006200 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006201 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6202 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006203 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x
Michael Wright842500e2015-03-13 17:32:02 -07006204 - mLastRawState.rawPointerData.pointers[lastIndex].x)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 * mPointerXMovementScale;
Jun Mukaifa1706a2015-12-03 01:14:46 -08006206 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y
Michael Wright842500e2015-03-13 17:32:02 -07006207 - mLastRawState.rawPointerData.pointers[lastIndex].y)
Michael Wrightd02c5b62014-02-10 15:10:22 -08006208 * mPointerYMovementScale;
6209
6210 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6211 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6212
6213 mPointerController->move(deltaX, deltaY);
6214 } else {
6215 mPointerVelocityControl.reset();
6216 }
6217
Michael Wright842500e2015-03-13 17:32:02 -07006218 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006219 hovering = !down;
6220
6221 float x, y;
6222 mPointerController->getPosition(&x, &y);
6223 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006224 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006225 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6226 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6227 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6228 hovering ? 0.0f : 1.0f);
6229 mPointerSimple.currentProperties.id = 0;
6230 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006231 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006232 } else {
6233 mPointerVelocityControl.reset();
6234
6235 down = false;
6236 hovering = false;
6237 }
6238
6239 dispatchPointerSimple(when, policyFlags, down, hovering);
6240}
6241
6242void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6243 abortPointerSimple(when, policyFlags);
6244
6245 mPointerVelocityControl.reset();
6246}
6247
6248void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags,
6249 bool down, bool hovering) {
6250 int32_t metaState = getContext()->getGlobalMetaState();
6251
Yi Kong9b14ac62018-07-17 13:48:38 -07006252 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006253 if (down || hovering) {
6254 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6255 mPointerController->clearSpots();
Michael Wright842500e2015-03-13 17:32:02 -07006256 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006257 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6258 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6259 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6260 }
6261 }
6262
6263 if (mPointerSimple.down && !down) {
6264 mPointerSimple.down = false;
6265
6266 // Send up.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006267 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006268 AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006269 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006270 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6271 mOrientedXPrecision, mOrientedYPrecision,
6272 mPointerSimple.downTime);
6273 getListener()->notifyMotion(&args);
6274 }
6275
6276 if (mPointerSimple.hovering && !hovering) {
6277 mPointerSimple.hovering = false;
6278
6279 // Send hover exit.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006280 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006281 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006282 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006283 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
6284 mOrientedXPrecision, mOrientedYPrecision,
6285 mPointerSimple.downTime);
6286 getListener()->notifyMotion(&args);
6287 }
6288
6289 if (down) {
6290 if (!mPointerSimple.down) {
6291 mPointerSimple.down = true;
6292 mPointerSimple.downTime = when;
6293
6294 // Send down.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006295 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006296 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006297 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006298 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6299 mOrientedXPrecision, mOrientedYPrecision,
6300 mPointerSimple.downTime);
6301 getListener()->notifyMotion(&args);
6302 }
6303
6304 // Send move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006305 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006306 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006307 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006308 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6309 mOrientedXPrecision, mOrientedYPrecision,
6310 mPointerSimple.downTime);
6311 getListener()->notifyMotion(&args);
6312 }
6313
6314 if (hovering) {
6315 if (!mPointerSimple.hovering) {
6316 mPointerSimple.hovering = true;
6317
6318 // Send hover enter.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006319 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006320 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006321 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006322 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006323 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6324 mOrientedXPrecision, mOrientedYPrecision,
6325 mPointerSimple.downTime);
6326 getListener()->notifyMotion(&args);
6327 }
6328
6329 // Send hover move.
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006330 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006331 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
Michael Wright842500e2015-03-13 17:32:02 -07006332 mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006333 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006334 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6335 mOrientedXPrecision, mOrientedYPrecision,
6336 mPointerSimple.downTime);
6337 getListener()->notifyMotion(&args);
6338 }
6339
Michael Wright842500e2015-03-13 17:32:02 -07006340 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6341 float vscroll = mCurrentRawState.rawVScroll;
6342 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006343 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6344 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345
6346 // Send scroll.
6347 PointerCoords pointerCoords;
6348 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6349 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6350 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6351
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006352 NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006353 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006354 /* deviceTimestamp */ 0,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006355 1, &mPointerSimple.currentProperties, &pointerCoords,
6356 mOrientedXPrecision, mOrientedYPrecision,
6357 mPointerSimple.downTime);
6358 getListener()->notifyMotion(&args);
6359 }
6360
6361 // Save state.
6362 if (down || hovering) {
6363 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6364 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6365 } else {
6366 mPointerSimple.reset();
6367 }
6368}
6369
6370void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6371 mPointerSimple.currentCoords.clear();
6372 mPointerSimple.currentProperties.clear();
6373
6374 dispatchPointerSimple(when, policyFlags, false, false);
6375}
6376
6377void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Michael Wright7b159c92015-05-14 14:48:03 +01006378 int32_t action, int32_t actionButton, int32_t flags,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006379 int32_t metaState, int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006380 const PointerProperties* properties, const PointerCoords* coords,
Michael Wright7b159c92015-05-14 14:48:03 +01006381 const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId,
6382 float xPrecision, float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006383 PointerCoords pointerCoords[MAX_POINTERS];
6384 PointerProperties pointerProperties[MAX_POINTERS];
6385 uint32_t pointerCount = 0;
6386 while (!idBits.isEmpty()) {
6387 uint32_t id = idBits.clearFirstMarkedBit();
6388 uint32_t index = idToIndex[id];
6389 pointerProperties[pointerCount].copyFrom(properties[index]);
6390 pointerCoords[pointerCount].copyFrom(coords[index]);
6391
6392 if (changedId >= 0 && id == uint32_t(changedId)) {
6393 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6394 }
6395
6396 pointerCount += 1;
6397 }
6398
6399 ALOG_ASSERT(pointerCount != 0);
6400
6401 if (changedId >= 0 && pointerCount == 1) {
6402 // Replace initial down and final up action.
6403 // We can compare the action without masking off the changed pointer index
6404 // because we know the index is 0.
6405 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6406 action = AMOTION_EVENT_ACTION_DOWN;
6407 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6408 action = AMOTION_EVENT_ACTION_UP;
6409 } else {
6410 // Can't happen.
6411 ALOG_ASSERT(false);
6412 }
6413 }
6414
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006415 NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01006416 action, actionButton, flags, metaState, buttonState, edgeFlags,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08006417 deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006418 xPrecision, yPrecision, downTime);
6419 getListener()->notifyMotion(&args);
6420}
6421
6422bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
6423 const PointerCoords* inCoords, const uint32_t* inIdToIndex,
6424 PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex,
6425 BitSet32 idBits) const {
6426 bool changed = false;
6427 while (!idBits.isEmpty()) {
6428 uint32_t id = idBits.clearFirstMarkedBit();
6429 uint32_t inIndex = inIdToIndex[id];
6430 uint32_t outIndex = outIdToIndex[id];
6431
6432 const PointerProperties& curInProperties = inProperties[inIndex];
6433 const PointerCoords& curInCoords = inCoords[inIndex];
6434 PointerProperties& curOutProperties = outProperties[outIndex];
6435 PointerCoords& curOutCoords = outCoords[outIndex];
6436
6437 if (curInProperties != curOutProperties) {
6438 curOutProperties.copyFrom(curInProperties);
6439 changed = true;
6440 }
6441
6442 if (curInCoords != curOutCoords) {
6443 curOutCoords.copyFrom(curInCoords);
6444 changed = true;
6445 }
6446 }
6447 return changed;
6448}
6449
6450void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006451 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006452 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6453 }
6454}
6455
Jeff Brownc9aa6282015-02-11 19:03:28 -08006456void TouchInputMapper::cancelTouch(nsecs_t when) {
6457 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006458 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006459}
6460
Michael Wrightd02c5b62014-02-10 15:10:22 -08006461bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006462 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006463 const float scaledY = y * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006464 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue
Michael Wright358bcc72018-08-21 04:01:07 +01006465 && scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth
6466 && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue
6467 && scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006468}
6469
6470const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(
6471 int32_t x, int32_t y) {
6472 size_t numVirtualKeys = mVirtualKeys.size();
6473 for (size_t i = 0; i < numVirtualKeys; i++) {
6474 const VirtualKey& virtualKey = mVirtualKeys[i];
6475
6476#if DEBUG_VIRTUAL_KEYS
6477 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
6478 "left=%d, top=%d, right=%d, bottom=%d",
6479 x, y,
6480 virtualKey.keyCode, virtualKey.scanCode,
6481 virtualKey.hitLeft, virtualKey.hitTop,
6482 virtualKey.hitRight, virtualKey.hitBottom);
6483#endif
6484
6485 if (virtualKey.isHit(x, y)) {
6486 return & virtualKey;
6487 }
6488 }
6489
Yi Kong9b14ac62018-07-17 13:48:38 -07006490 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006491}
6492
Michael Wright842500e2015-03-13 17:32:02 -07006493void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6494 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6495 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006496
Michael Wright842500e2015-03-13 17:32:02 -07006497 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006498
6499 if (currentPointerCount == 0) {
6500 // No pointers to assign.
6501 return;
6502 }
6503
6504 if (lastPointerCount == 0) {
6505 // All pointers are new.
6506 for (uint32_t i = 0; i < currentPointerCount; i++) {
6507 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006508 current->rawPointerData.pointers[i].id = id;
6509 current->rawPointerData.idToIndex[id] = i;
6510 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006511 }
6512 return;
6513 }
6514
6515 if (currentPointerCount == 1 && lastPointerCount == 1
Michael Wright842500e2015-03-13 17:32:02 -07006516 && current->rawPointerData.pointers[0].toolType
6517 == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006518 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006519 uint32_t id = last->rawPointerData.pointers[0].id;
6520 current->rawPointerData.pointers[0].id = id;
6521 current->rawPointerData.idToIndex[id] = 0;
6522 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006523 return;
6524 }
6525
6526 // General case.
6527 // We build a heap of squared euclidean distances between current and last pointers
6528 // associated with the current and last pointer indices. Then, we find the best
6529 // match (by distance) for each current pointer.
6530 // The pointers must have the same tool type but it is possible for them to
6531 // transition from hovering to touching or vice-versa while retaining the same id.
6532 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6533
6534 uint32_t heapSize = 0;
6535 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
6536 currentPointerIndex++) {
6537 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
6538 lastPointerIndex++) {
6539 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006540 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006541 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006542 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543 if (currentPointer.toolType == lastPointer.toolType) {
6544 int64_t deltaX = currentPointer.x - lastPointer.x;
6545 int64_t deltaY = currentPointer.y - lastPointer.y;
6546
6547 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6548
6549 // Insert new element into the heap (sift up).
6550 heap[heapSize].currentPointerIndex = currentPointerIndex;
6551 heap[heapSize].lastPointerIndex = lastPointerIndex;
6552 heap[heapSize].distance = distance;
6553 heapSize += 1;
6554 }
6555 }
6556 }
6557
6558 // Heapify
6559 for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) {
6560 startIndex -= 1;
6561 for (uint32_t parentIndex = startIndex; ;) {
6562 uint32_t childIndex = parentIndex * 2 + 1;
6563 if (childIndex >= heapSize) {
6564 break;
6565 }
6566
6567 if (childIndex + 1 < heapSize
6568 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6569 childIndex += 1;
6570 }
6571
6572 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6573 break;
6574 }
6575
6576 swap(heap[parentIndex], heap[childIndex]);
6577 parentIndex = childIndex;
6578 }
6579 }
6580
6581#if DEBUG_POINTER_ASSIGNMENT
6582 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6583 for (size_t i = 0; i < heapSize; i++) {
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006584 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006585 i, heap[i].currentPointerIndex, heap[i].lastPointerIndex,
6586 heap[i].distance);
6587 }
6588#endif
6589
6590 // Pull matches out by increasing order of distance.
6591 // To avoid reassigning pointers that have already been matched, the loop keeps track
6592 // of which last and current pointers have been matched using the matchedXXXBits variables.
6593 // It also tracks the used pointer id bits.
6594 BitSet32 matchedLastBits(0);
6595 BitSet32 matchedCurrentBits(0);
6596 BitSet32 usedIdBits(0);
6597 bool first = true;
6598 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6599 while (heapSize > 0) {
6600 if (first) {
6601 // The first time through the loop, we just consume the root element of
6602 // the heap (the one with smallest distance).
6603 first = false;
6604 } else {
6605 // Previous iterations consumed the root element of the heap.
6606 // Pop root element off of the heap (sift down).
6607 heap[0] = heap[heapSize];
6608 for (uint32_t parentIndex = 0; ;) {
6609 uint32_t childIndex = parentIndex * 2 + 1;
6610 if (childIndex >= heapSize) {
6611 break;
6612 }
6613
6614 if (childIndex + 1 < heapSize
6615 && heap[childIndex + 1].distance < heap[childIndex].distance) {
6616 childIndex += 1;
6617 }
6618
6619 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6620 break;
6621 }
6622
6623 swap(heap[parentIndex], heap[childIndex]);
6624 parentIndex = childIndex;
6625 }
6626
6627#if DEBUG_POINTER_ASSIGNMENT
6628 ALOGD("assignPointerIds - reduced 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
6637 heapSize -= 1;
6638
6639 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6640 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6641
6642 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6643 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6644
6645 matchedCurrentBits.markBit(currentPointerIndex);
6646 matchedLastBits.markBit(lastPointerIndex);
6647
Michael Wright842500e2015-03-13 17:32:02 -07006648 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6649 current->rawPointerData.pointers[currentPointerIndex].id = id;
6650 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6651 current->rawPointerData.markIdBit(id,
6652 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006653 usedIdBits.markBit(id);
6654
6655#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006656 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32
6657 ", id=%" PRIu32 ", distance=%" PRIu64,
Michael Wrightd02c5b62014-02-10 15:10:22 -08006658 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
6659#endif
6660 break;
6661 }
6662 }
6663
6664 // Assign fresh ids to pointers that were not matched in the process.
6665 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6666 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6667 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6668
Michael Wright842500e2015-03-13 17:32:02 -07006669 current->rawPointerData.pointers[currentPointerIndex].id = id;
6670 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6671 current->rawPointerData.markIdBit(id,
6672 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006673
6674#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006675 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006676#endif
6677 }
6678}
6679
6680int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6681 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6682 return AKEY_STATE_VIRTUAL;
6683 }
6684
6685 size_t numVirtualKeys = mVirtualKeys.size();
6686 for (size_t i = 0; i < numVirtualKeys; i++) {
6687 const VirtualKey& virtualKey = mVirtualKeys[i];
6688 if (virtualKey.keyCode == keyCode) {
6689 return AKEY_STATE_UP;
6690 }
6691 }
6692
6693 return AKEY_STATE_UNKNOWN;
6694}
6695
6696int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6697 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6698 return AKEY_STATE_VIRTUAL;
6699 }
6700
6701 size_t numVirtualKeys = mVirtualKeys.size();
6702 for (size_t i = 0; i < numVirtualKeys; i++) {
6703 const VirtualKey& virtualKey = mVirtualKeys[i];
6704 if (virtualKey.scanCode == scanCode) {
6705 return AKEY_STATE_UP;
6706 }
6707 }
6708
6709 return AKEY_STATE_UNKNOWN;
6710}
6711
6712bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
6713 const int32_t* keyCodes, uint8_t* outFlags) {
6714 size_t numVirtualKeys = mVirtualKeys.size();
6715 for (size_t i = 0; i < numVirtualKeys; i++) {
6716 const VirtualKey& virtualKey = mVirtualKeys[i];
6717
6718 for (size_t i = 0; i < numCodes; i++) {
6719 if (virtualKey.keyCode == keyCodes[i]) {
6720 outFlags[i] = 1;
6721 }
6722 }
6723 }
6724
6725 return true;
6726}
6727
6728
6729// --- SingleTouchInputMapper ---
6730
6731SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) :
6732 TouchInputMapper(device) {
6733}
6734
6735SingleTouchInputMapper::~SingleTouchInputMapper() {
6736}
6737
6738void SingleTouchInputMapper::reset(nsecs_t when) {
6739 mSingleTouchMotionAccumulator.reset(getDevice());
6740
6741 TouchInputMapper::reset(when);
6742}
6743
6744void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6745 TouchInputMapper::process(rawEvent);
6746
6747 mSingleTouchMotionAccumulator.process(rawEvent);
6748}
6749
Michael Wright842500e2015-03-13 17:32:02 -07006750void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006751 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006752 outState->rawPointerData.pointerCount = 1;
6753 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006754
6755 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6756 && (mTouchButtonAccumulator.isHovering()
6757 || (mRawPointerAxes.pressure.valid
6758 && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006759 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006760
Michael Wright842500e2015-03-13 17:32:02 -07006761 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006762 outPointer.id = 0;
6763 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6764 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6765 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6766 outPointer.touchMajor = 0;
6767 outPointer.touchMinor = 0;
6768 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6769 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6770 outPointer.orientation = 0;
6771 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6772 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6773 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6774 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6775 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6776 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6777 }
6778 outPointer.isHovering = isHovering;
6779 }
6780}
6781
6782void SingleTouchInputMapper::configureRawPointerAxes() {
6783 TouchInputMapper::configureRawPointerAxes();
6784
6785 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6786 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6787 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6788 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6789 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6790 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6791 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6792}
6793
6794bool SingleTouchInputMapper::hasStylus() const {
6795 return mTouchButtonAccumulator.hasStylus();
6796}
6797
6798
6799// --- MultiTouchInputMapper ---
6800
6801MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) :
6802 TouchInputMapper(device) {
6803}
6804
6805MultiTouchInputMapper::~MultiTouchInputMapper() {
6806}
6807
6808void MultiTouchInputMapper::reset(nsecs_t when) {
6809 mMultiTouchMotionAccumulator.reset(getDevice());
6810
6811 mPointerIdBits.clear();
6812
6813 TouchInputMapper::reset(when);
6814}
6815
6816void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6817 TouchInputMapper::process(rawEvent);
6818
6819 mMultiTouchMotionAccumulator.process(rawEvent);
6820}
6821
Michael Wright842500e2015-03-13 17:32:02 -07006822void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006823 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6824 size_t outCount = 0;
6825 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006826 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006827
6828 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6829 const MultiTouchMotionAccumulator::Slot* inSlot =
6830 mMultiTouchMotionAccumulator.getSlot(inIndex);
6831 if (!inSlot->isInUse()) {
6832 continue;
6833 }
6834
6835 if (outCount >= MAX_POINTERS) {
6836#if DEBUG_POINTERS
6837 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
6838 "ignoring the rest.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006839 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006840#endif
6841 break; // too many fingers!
6842 }
6843
Michael Wright842500e2015-03-13 17:32:02 -07006844 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006845 outPointer.x = inSlot->getX();
6846 outPointer.y = inSlot->getY();
6847 outPointer.pressure = inSlot->getPressure();
6848 outPointer.touchMajor = inSlot->getTouchMajor();
6849 outPointer.touchMinor = inSlot->getTouchMinor();
6850 outPointer.toolMajor = inSlot->getToolMajor();
6851 outPointer.toolMinor = inSlot->getToolMinor();
6852 outPointer.orientation = inSlot->getOrientation();
6853 outPointer.distance = inSlot->getDistance();
6854 outPointer.tiltX = 0;
6855 outPointer.tiltY = 0;
6856
6857 outPointer.toolType = inSlot->getToolType();
6858 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6859 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6860 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6861 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6862 }
6863 }
6864
6865 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE
6866 && (mTouchButtonAccumulator.isHovering()
6867 || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
6868 outPointer.isHovering = isHovering;
6869
6870 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006871 if (mHavePointerIds) {
6872 int32_t trackingId = inSlot->getTrackingId();
6873 int32_t id = -1;
6874 if (trackingId >= 0) {
6875 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) {
6876 uint32_t n = idBits.clearFirstMarkedBit();
6877 if (mPointerTrackingIdMap[n] == trackingId) {
6878 id = n;
6879 }
6880 }
6881
6882 if (id < 0 && !mPointerIdBits.isFull()) {
6883 id = mPointerIdBits.markFirstUnmarkedBit();
6884 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006885 }
Michael Wright842500e2015-03-13 17:32:02 -07006886 }
gaoshang1a632de2016-08-24 10:23:50 +08006887 if (id < 0) {
6888 mHavePointerIds = false;
6889 outState->rawPointerData.clearIdBits();
6890 newPointerIdBits.clear();
6891 } else {
6892 outPointer.id = id;
6893 outState->rawPointerData.idToIndex[id] = outCount;
6894 outState->rawPointerData.markIdBit(id, isHovering);
6895 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006896 }
Michael Wright842500e2015-03-13 17:32:02 -07006897 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006898 outCount += 1;
6899 }
6900
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08006901 outState->deviceTimestamp = mMultiTouchMotionAccumulator.getDeviceTimestamp();
Michael Wright842500e2015-03-13 17:32:02 -07006902 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006903 mPointerIdBits = newPointerIdBits;
6904
6905 mMultiTouchMotionAccumulator.finishSync();
6906}
6907
6908void MultiTouchInputMapper::configureRawPointerAxes() {
6909 TouchInputMapper::configureRawPointerAxes();
6910
6911 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6912 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6913 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6914 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6915 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6916 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6917 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6918 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6919 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6920 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6921 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6922
6923 if (mRawPointerAxes.trackingId.valid
6924 && mRawPointerAxes.slot.valid
6925 && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
6926 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6927 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006928 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
6929 "only supports a maximum of %zu slots at this time.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01006930 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006931 slotCount = MAX_SLOTS;
6932 }
6933 mMultiTouchMotionAccumulator.configure(getDevice(),
6934 slotCount, true /*usingSlotsProtocol*/);
6935 } else {
6936 mMultiTouchMotionAccumulator.configure(getDevice(),
6937 MAX_POINTERS, false /*usingSlotsProtocol*/);
6938 }
6939}
6940
6941bool MultiTouchInputMapper::hasStylus() const {
6942 return mMultiTouchMotionAccumulator.hasStylus()
6943 || mTouchButtonAccumulator.hasStylus();
6944}
6945
Michael Wright842500e2015-03-13 17:32:02 -07006946// --- ExternalStylusInputMapper
6947
6948ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) :
6949 InputMapper(device) {
6950
6951}
6952
6953uint32_t ExternalStylusInputMapper::getSources() {
6954 return AINPUT_SOURCE_STYLUS;
6955}
6956
6957void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
6958 InputMapper::populateDeviceInfo(info);
6959 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS,
6960 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
6961}
6962
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006963void ExternalStylusInputMapper::dump(std::string& dump) {
6964 dump += INDENT2 "External Stylus Input Mapper:\n";
6965 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07006966 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08006967 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07006968 dumpStylusState(dump, mStylusState);
6969}
6970
6971void ExternalStylusInputMapper::configure(nsecs_t when,
6972 const InputReaderConfiguration* config, uint32_t changes) {
6973 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
6974 mTouchButtonAccumulator.configure(getDevice());
6975}
6976
6977void ExternalStylusInputMapper::reset(nsecs_t when) {
6978 InputDevice* device = getDevice();
6979 mSingleTouchMotionAccumulator.reset(device);
6980 mTouchButtonAccumulator.reset(device);
6981 InputMapper::reset(when);
6982}
6983
6984void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
6985 mSingleTouchMotionAccumulator.process(rawEvent);
6986 mTouchButtonAccumulator.process(rawEvent);
6987
6988 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
6989 sync(rawEvent->when);
6990 }
6991}
6992
6993void ExternalStylusInputMapper::sync(nsecs_t when) {
6994 mStylusState.clear();
6995
6996 mStylusState.when = when;
6997
Michael Wright45ccacf2015-04-21 19:01:58 +01006998 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
6999 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7000 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7001 }
7002
Michael Wright842500e2015-03-13 17:32:02 -07007003 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7004 if (mRawPressureAxis.valid) {
7005 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7006 } else if (mTouchButtonAccumulator.isToolActive()) {
7007 mStylusState.pressure = 1.0f;
7008 } else {
7009 mStylusState.pressure = 0.0f;
7010 }
7011
7012 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007013
7014 mContext->dispatchExternalStylusState(mStylusState);
7015}
7016
Michael Wrightd02c5b62014-02-10 15:10:22 -08007017
7018// --- JoystickInputMapper ---
7019
7020JoystickInputMapper::JoystickInputMapper(InputDevice* device) :
7021 InputMapper(device) {
7022}
7023
7024JoystickInputMapper::~JoystickInputMapper() {
7025}
7026
7027uint32_t JoystickInputMapper::getSources() {
7028 return AINPUT_SOURCE_JOYSTICK;
7029}
7030
7031void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7032 InputMapper::populateDeviceInfo(info);
7033
7034 for (size_t i = 0; i < mAxes.size(); i++) {
7035 const Axis& axis = mAxes.valueAt(i);
7036 addMotionRange(axis.axisInfo.axis, axis, info);
7037
7038 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7039 addMotionRange(axis.axisInfo.highAxis, axis, info);
7040
7041 }
7042 }
7043}
7044
7045void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis,
7046 InputDeviceInfo* info) {
7047 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK,
7048 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7049 /* In order to ease the transition for developers from using the old axes
7050 * to the newer, more semantically correct axes, we'll continue to register
7051 * the old axes as duplicates of their corresponding new ones. */
7052 int32_t compatAxis = getCompatAxis(axisId);
7053 if (compatAxis >= 0) {
7054 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK,
7055 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
7056 }
7057}
7058
7059/* A mapping from axes the joystick actually has to the axes that should be
7060 * artificially created for compatibility purposes.
7061 * Returns -1 if no compatibility axis is needed. */
7062int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
7063 switch(axis) {
7064 case AMOTION_EVENT_AXIS_LTRIGGER:
7065 return AMOTION_EVENT_AXIS_BRAKE;
7066 case AMOTION_EVENT_AXIS_RTRIGGER:
7067 return AMOTION_EVENT_AXIS_GAS;
7068 }
7069 return -1;
7070}
7071
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007072void JoystickInputMapper::dump(std::string& dump) {
7073 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007074
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007075 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007076 size_t numAxes = mAxes.size();
7077 for (size_t i = 0; i < numAxes; i++) {
7078 const Axis& axis = mAxes.valueAt(i);
7079 const char* label = getAxisLabel(axis.axisInfo.axis);
7080 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007081 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007082 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007083 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007084 }
7085 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7086 label = getAxisLabel(axis.axisInfo.highAxis);
7087 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007088 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007089 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007090 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Michael Wrightd02c5b62014-02-10 15:10:22 -08007091 axis.axisInfo.splitValue);
7092 }
7093 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007094 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007095 }
7096
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007097 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 -08007098 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007099 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007100 "highScale=%0.5f, highOffset=%0.5f\n",
7101 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007102 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Michael Wrightd02c5b62014-02-10 15:10:22 -08007103 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7104 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7105 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution);
7106 }
7107}
7108
7109void JoystickInputMapper::configure(nsecs_t when,
7110 const InputReaderConfiguration* config, uint32_t changes) {
7111 InputMapper::configure(when, config, changes);
7112
7113 if (!changes) { // first time only
7114 // Collect all axes.
7115 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
7116 if (!(getAbsAxisUsage(abs, getDevice()->getClasses())
7117 & INPUT_DEVICE_CLASS_JOYSTICK)) {
7118 continue; // axis must be claimed by a different device
7119 }
7120
7121 RawAbsoluteAxisInfo rawAxisInfo;
7122 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7123 if (rawAxisInfo.valid) {
7124 // Map axis.
7125 AxisInfo axisInfo;
7126 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7127 if (!explicitlyMapped) {
7128 // Axis is not explicitly mapped, will choose a generic axis later.
7129 axisInfo.mode = AxisInfo::MODE_NORMAL;
7130 axisInfo.axis = -1;
7131 }
7132
7133 // Apply flat override.
7134 int32_t rawFlat = axisInfo.flatOverride < 0
7135 ? rawAxisInfo.flat : axisInfo.flatOverride;
7136
7137 // Calculate scaling factors and limits.
7138 Axis axis;
7139 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7140 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7141 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
7142 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7143 scale, 0.0f, highScale, 0.0f,
7144 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7145 rawAxisInfo.resolution * scale);
7146 } else if (isCenteredAxis(axisInfo.axis)) {
7147 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7148 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
7149 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7150 scale, offset, scale, offset,
7151 -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7152 rawAxisInfo.resolution * scale);
7153 } else {
7154 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7155 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped,
7156 scale, 0.0f, scale, 0.0f,
7157 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7158 rawAxisInfo.resolution * scale);
7159 }
7160
7161 // To eliminate noise while the joystick is at rest, filter out small variations
7162 // in axis values up front.
7163 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7164
7165 mAxes.add(abs, axis);
7166 }
7167 }
7168
7169 // If there are too many axes, start dropping them.
7170 // Prefer to keep explicitly mapped axes.
7171 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007172 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007173 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007174 pruneAxes(true);
7175 pruneAxes(false);
7176 }
7177
7178 // Assign generic axis ids to remaining axes.
7179 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7180 size_t numAxes = mAxes.size();
7181 for (size_t i = 0; i < numAxes; i++) {
7182 Axis& axis = mAxes.editValueAt(i);
7183 if (axis.axisInfo.axis < 0) {
7184 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16
7185 && haveAxis(nextGenericAxisId)) {
7186 nextGenericAxisId += 1;
7187 }
7188
7189 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7190 axis.axisInfo.axis = nextGenericAxisId;
7191 nextGenericAxisId += 1;
7192 } else {
7193 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
7194 "have already been assigned to other axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007195 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007196 mAxes.removeItemsAt(i--);
7197 numAxes -= 1;
7198 }
7199 }
7200 }
7201 }
7202}
7203
7204bool JoystickInputMapper::haveAxis(int32_t axisId) {
7205 size_t numAxes = mAxes.size();
7206 for (size_t i = 0; i < numAxes; i++) {
7207 const Axis& axis = mAxes.valueAt(i);
7208 if (axis.axisInfo.axis == axisId
7209 || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT
7210 && axis.axisInfo.highAxis == axisId)) {
7211 return true;
7212 }
7213 }
7214 return false;
7215}
7216
7217void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7218 size_t i = mAxes.size();
7219 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7220 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7221 continue;
7222 }
7223 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01007224 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007225 mAxes.removeItemsAt(i);
7226 }
7227}
7228
7229bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7230 switch (axis) {
7231 case AMOTION_EVENT_AXIS_X:
7232 case AMOTION_EVENT_AXIS_Y:
7233 case AMOTION_EVENT_AXIS_Z:
7234 case AMOTION_EVENT_AXIS_RX:
7235 case AMOTION_EVENT_AXIS_RY:
7236 case AMOTION_EVENT_AXIS_RZ:
7237 case AMOTION_EVENT_AXIS_HAT_X:
7238 case AMOTION_EVENT_AXIS_HAT_Y:
7239 case AMOTION_EVENT_AXIS_ORIENTATION:
7240 case AMOTION_EVENT_AXIS_RUDDER:
7241 case AMOTION_EVENT_AXIS_WHEEL:
7242 return true;
7243 default:
7244 return false;
7245 }
7246}
7247
7248void JoystickInputMapper::reset(nsecs_t when) {
7249 // Recenter all axes.
7250 size_t numAxes = mAxes.size();
7251 for (size_t i = 0; i < numAxes; i++) {
7252 Axis& axis = mAxes.editValueAt(i);
7253 axis.resetValue();
7254 }
7255
7256 InputMapper::reset(when);
7257}
7258
7259void JoystickInputMapper::process(const RawEvent* rawEvent) {
7260 switch (rawEvent->type) {
7261 case EV_ABS: {
7262 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7263 if (index >= 0) {
7264 Axis& axis = mAxes.editValueAt(index);
7265 float newValue, highNewValue;
7266 switch (axis.axisInfo.mode) {
7267 case AxisInfo::MODE_INVERT:
7268 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value)
7269 * axis.scale + axis.offset;
7270 highNewValue = 0.0f;
7271 break;
7272 case AxisInfo::MODE_SPLIT:
7273 if (rawEvent->value < axis.axisInfo.splitValue) {
7274 newValue = (axis.axisInfo.splitValue - rawEvent->value)
7275 * axis.scale + axis.offset;
7276 highNewValue = 0.0f;
7277 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7278 newValue = 0.0f;
7279 highNewValue = (rawEvent->value - axis.axisInfo.splitValue)
7280 * axis.highScale + axis.highOffset;
7281 } else {
7282 newValue = 0.0f;
7283 highNewValue = 0.0f;
7284 }
7285 break;
7286 default:
7287 newValue = rawEvent->value * axis.scale + axis.offset;
7288 highNewValue = 0.0f;
7289 break;
7290 }
7291 axis.newValue = newValue;
7292 axis.highNewValue = highNewValue;
7293 }
7294 break;
7295 }
7296
7297 case EV_SYN:
7298 switch (rawEvent->code) {
7299 case SYN_REPORT:
7300 sync(rawEvent->when, false /*force*/);
7301 break;
7302 }
7303 break;
7304 }
7305}
7306
7307void JoystickInputMapper::sync(nsecs_t when, bool force) {
7308 if (!filterAxes(force)) {
7309 return;
7310 }
7311
7312 int32_t metaState = mContext->getGlobalMetaState();
7313 int32_t buttonState = 0;
7314
7315 PointerProperties pointerProperties;
7316 pointerProperties.clear();
7317 pointerProperties.id = 0;
7318 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7319
7320 PointerCoords pointerCoords;
7321 pointerCoords.clear();
7322
7323 size_t numAxes = mAxes.size();
7324 for (size_t i = 0; i < numAxes; i++) {
7325 const Axis& axis = mAxes.valueAt(i);
7326 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7327 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7328 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
7329 axis.highCurrentValue);
7330 }
7331 }
7332
7333 // Moving a joystick axis should not wake the device because joysticks can
7334 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7335 // button will likely wake the device.
7336 // TODO: Use the input device configuration to control this behavior more finely.
7337 uint32_t policyFlags = 0;
7338
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007339 NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
7340 policyFlags,
Michael Wright7b159c92015-05-14 14:48:03 +01007341 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08007342 /* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
Siarhei Vishniakou16f90692017-12-27 14:29:55 -08007343 0, 0, 0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007344 getListener()->notifyMotion(&args);
7345}
7346
7347void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords,
7348 int32_t axis, float value) {
7349 pointerCoords->setAxisValue(axis, value);
7350 /* In order to ease the transition for developers from using the old axes
7351 * to the newer, more semantically correct axes, we'll continue to produce
7352 * values for the old axes as mirrors of the value of their corresponding
7353 * new axes. */
7354 int32_t compatAxis = getCompatAxis(axis);
7355 if (compatAxis >= 0) {
7356 pointerCoords->setAxisValue(compatAxis, value);
7357 }
7358}
7359
7360bool JoystickInputMapper::filterAxes(bool force) {
7361 bool atLeastOneSignificantChange = force;
7362 size_t numAxes = mAxes.size();
7363 for (size_t i = 0; i < numAxes; i++) {
7364 Axis& axis = mAxes.editValueAt(i);
7365 if (force || hasValueChangedSignificantly(axis.filter,
7366 axis.newValue, axis.currentValue, axis.min, axis.max)) {
7367 axis.currentValue = axis.newValue;
7368 atLeastOneSignificantChange = true;
7369 }
7370 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7371 if (force || hasValueChangedSignificantly(axis.filter,
7372 axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) {
7373 axis.highCurrentValue = axis.highNewValue;
7374 atLeastOneSignificantChange = true;
7375 }
7376 }
7377 }
7378 return atLeastOneSignificantChange;
7379}
7380
7381bool JoystickInputMapper::hasValueChangedSignificantly(
7382 float filter, float newValue, float currentValue, float min, float max) {
7383 if (newValue != currentValue) {
7384 // Filter out small changes in value unless the value is converging on the axis
7385 // bounds or center point. This is intended to reduce the amount of information
7386 // sent to applications by particularly noisy joysticks (such as PS3).
7387 if (fabs(newValue - currentValue) > filter
7388 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min)
7389 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max)
7390 || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
7391 return true;
7392 }
7393 }
7394 return false;
7395}
7396
7397bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(
7398 float filter, float newValue, float currentValue, float thresholdValue) {
7399 float newDistance = fabs(newValue - thresholdValue);
7400 if (newDistance < filter) {
7401 float oldDistance = fabs(currentValue - thresholdValue);
7402 if (newDistance < oldDistance) {
7403 return true;
7404 }
7405 }
7406 return false;
7407}
7408
7409} // namespace android