blob: 521f621dea16726395aae093d3600c25559c6ea9 [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.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080074static constexpr size_t MAX_SLOTS = 32;
Michael Wrightd02c5b62014-02-10 15:10:22 -080075
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.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080078static constexpr 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.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080081static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
Michael Wright43fd19f2015-04-21 19:02:58 +010082
83// Artificial latency on synthetic events created from stylus data without corresponding touch
84// data.
Siarhei Vishniakou9ffab0c2018-11-08 19:54:22 -080085static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
86
Michael Wrightd02c5b62014-02-10 15:10:22 -080087// --- Static Functions ---
88
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070089template <typename T>
Michael Wrightd02c5b62014-02-10 15:10:22 -080090inline static T abs(const T& value) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070091 return value < 0 ? -value : value;
Michael Wrightd02c5b62014-02-10 15:10:22 -080092}
93
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070094template <typename T>
Michael Wrightd02c5b62014-02-10 15:10:22 -080095inline static T min(const T& a, const T& b) {
96 return a < b ? a : b;
97}
98
Prabir Pradhanda7c00c2019-08-29 14:12:42 -070099template <typename T>
Michael Wrightd02c5b62014-02-10 15:10:22 -0800100inline 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,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700123 const int32_t map[][4], size_t mapSize) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800124 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
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700137 {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},
141 {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
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700153static int32_t rotateStemKey(int32_t value, int32_t orientation, const int32_t map[][2],
154 size_t mapSize) {
Ivan Podogovb9afef32017-02-13 15:34:32 +0000155 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
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700169 {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},
Ivan Podogovb9afef32017-02-13 15:34:32 +0000173};
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) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700178 keyCode = rotateStemKey(keyCode, orientation, stemKeyRotationMap, stemKeyRotationMapSize);
179 return rotateValueUsingRotationMap(keyCode, orientation, keyCodeRotationMap,
180 keyCodeRotationMapSize);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800181}
182
183static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) {
184 float temp;
185 switch (orientation) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700186 case DISPLAY_ORIENTATION_90:
187 temp = *deltaX;
188 *deltaX = *deltaY;
189 *deltaY = -temp;
190 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800191
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700192 case DISPLAY_ORIENTATION_180:
193 *deltaX = -*deltaX;
194 *deltaY = -*deltaY;
195 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800196
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700197 case DISPLAY_ORIENTATION_270:
198 temp = *deltaX;
199 *deltaX = -*deltaY;
200 *deltaY = temp;
201 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800202 }
203}
204
205static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700206 return (sources & sourceMask & ~AINPUT_SOURCE_CLASS_MASK) != 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800207}
208
209// Returns true if the pointer should be reported as being down given the specified
210// button states. This determines whether the event is reported as a touch event.
211static bool isPointerDown(int32_t buttonState) {
212 return buttonState &
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700213 (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY |
214 AMOTION_EVENT_BUTTON_TERTIARY);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800215}
216
217static float calculateCommonVector(float a, float b) {
218 if (a > 0 && b > 0) {
219 return a < b ? a : b;
220 } else if (a < 0 && b < 0) {
221 return a > b ? a : b;
222 } else {
223 return 0;
224 }
225}
226
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700227static void synthesizeButtonKey(InputReaderContext* context, int32_t action, nsecs_t when,
228 int32_t deviceId, uint32_t source, int32_t displayId,
229 uint32_t policyFlags, int32_t lastButtonState,
230 int32_t currentButtonState, int32_t buttonState, int32_t keyCode) {
231 if ((action == AKEY_EVENT_ACTION_DOWN && !(lastButtonState & buttonState) &&
232 (currentButtonState & buttonState)) ||
233 (action == AKEY_EVENT_ACTION_UP && (lastButtonState & buttonState) &&
234 !(currentButtonState & buttonState))) {
Prabir Pradhan42611e02018-11-27 14:04:02 -0800235 NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700236 policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800237 context->getListener()->notifyKey(&args);
238 }
239}
240
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700241static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, nsecs_t when,
242 int32_t deviceId, uint32_t source, int32_t displayId,
243 uint32_t policyFlags, int32_t lastButtonState,
244 int32_t currentButtonState) {
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100245 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700246 lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_BACK,
247 AKEYCODE_BACK);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100248 synthesizeButtonKey(context, action, when, deviceId, source, displayId, policyFlags,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700249 lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_FORWARD,
250 AKEYCODE_FORWARD);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800251}
252
Michael Wrightd02c5b62014-02-10 15:10:22 -0800253// --- InputReader ---
254
Siarhei Vishniakou3bc7e092019-07-24 17:43:30 -0700255InputReader::InputReader(std::shared_ptr<EventHubInterface> eventHub,
256 const sp<InputReaderPolicyInterface>& policy,
257 const sp<InputListenerInterface>& listener)
258 : mContext(this),
259 mEventHub(eventHub),
260 mPolicy(policy),
261 mNextSequenceNum(1),
262 mGlobalMetaState(0),
263 mGeneration(1),
264 mDisableVirtualKeysTimeout(LLONG_MIN),
265 mNextTimeout(LLONG_MAX),
Michael Wrightd02c5b62014-02-10 15:10:22 -0800266 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;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800287 std::vector<InputDeviceInfo> inputDevices;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800288 { // 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) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700354 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT ||
355 rawEvent[batchSize].deviceId != deviceId) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800356 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) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700366 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;
Michael Wrightd02c5b62014-02-10 15:10:22 -0800378 }
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,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700402 identifier.name.c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800403 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700404 ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, identifier.name.c_str(),
405 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()) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700429 ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)", device->getId(),
430 device->getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800431 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700432 ALOGI("Device removed: id=%d, name='%s', sources=0x%08x", device->getId(),
433 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,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700445 const InputDeviceIdentifier& identifier,
446 uint32_t classes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800447 InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700448 controllerNumber, identifier, classes);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800449
450 // External devices.
451 if (classes & INPUT_DEVICE_CLASS_EXTERNAL) {
452 device->setExternal(true);
453 }
454
Tim Kilbourn063ff532015-04-08 10:26:18 -0700455 // Devices with mics.
456 if (classes & INPUT_DEVICE_CLASS_MIC) {
457 device->setMic(true);
458 }
459
Michael Wrightd02c5b62014-02-10 15:10:22 -0800460 // Switch-like devices.
461 if (classes & INPUT_DEVICE_CLASS_SWITCH) {
462 device->addMapper(new SwitchInputMapper(device));
463 }
464
Prashant Malani1941ff52015-08-11 18:29:28 -0700465 // Scroll wheel-like devices.
466 if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) {
467 device->addMapper(new RotaryEncoderInputMapper(device));
468 }
469
Michael Wrightd02c5b62014-02-10 15:10:22 -0800470 // Vibrator-like devices.
471 if (classes & INPUT_DEVICE_CLASS_VIBRATOR) {
472 device->addMapper(new VibratorInputMapper(device));
473 }
474
475 // Keyboard-like devices.
476 uint32_t keyboardSource = 0;
477 int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC;
478 if (classes & INPUT_DEVICE_CLASS_KEYBOARD) {
479 keyboardSource |= AINPUT_SOURCE_KEYBOARD;
480 }
481 if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) {
482 keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC;
483 }
484 if (classes & INPUT_DEVICE_CLASS_DPAD) {
485 keyboardSource |= AINPUT_SOURCE_DPAD;
486 }
487 if (classes & INPUT_DEVICE_CLASS_GAMEPAD) {
488 keyboardSource |= AINPUT_SOURCE_GAMEPAD;
489 }
490
491 if (keyboardSource != 0) {
492 device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType));
493 }
494
495 // Cursor-like devices.
496 if (classes & INPUT_DEVICE_CLASS_CURSOR) {
497 device->addMapper(new CursorInputMapper(device));
498 }
499
500 // Touchscreens and touchpad devices.
501 if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) {
502 device->addMapper(new MultiTouchInputMapper(device));
503 } else if (classes & INPUT_DEVICE_CLASS_TOUCH) {
504 device->addMapper(new SingleTouchInputMapper(device));
505 }
506
507 // Joystick-like devices.
508 if (classes & INPUT_DEVICE_CLASS_JOYSTICK) {
509 device->addMapper(new JoystickInputMapper(device));
510 }
511
Michael Wright842500e2015-03-13 17:32:02 -0700512 // External stylus-like devices.
513 if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) {
514 device->addMapper(new ExternalStylusInputMapper(device));
515 }
516
Michael Wrightd02c5b62014-02-10 15:10:22 -0800517 return device;
518}
519
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700520void InputReader::processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents,
521 size_t count) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800522 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
523 if (deviceIndex < 0) {
524 ALOGW("Discarding event for unknown deviceId %d.", deviceId);
525 return;
526 }
527
528 InputDevice* device = mDevices.valueAt(deviceIndex);
529 if (device->isIgnored()) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700530 // ALOGD("Discarding event for ignored deviceId %d.", deviceId);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800531 return;
532 }
533
534 device->process(rawEvents, count);
535}
536
537void InputReader::timeoutExpiredLocked(nsecs_t when) {
538 for (size_t i = 0; i < mDevices.size(); i++) {
539 InputDevice* device = mDevices.valueAt(i);
540 if (!device->isIgnored()) {
541 device->timeoutExpired(when);
542 }
543 }
544}
545
546void InputReader::handleConfigurationChangedLocked(nsecs_t when) {
547 // Reset global meta state because it depends on the list of all configured devices.
548 updateGlobalMetaStateLocked();
549
550 // Enqueue configuration changed.
Prabir Pradhan42611e02018-11-27 14:04:02 -0800551 NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800552 mQueuedListener->notifyConfigurationChanged(&args);
553}
554
555void InputReader::refreshConfigurationLocked(uint32_t changes) {
556 mPolicy->getReaderConfiguration(&mConfig);
557 mEventHub->setExcludedDevices(mConfig.excludedDeviceNames);
558
559 if (changes) {
Siarhei Vishniakouc5ae0dc2019-07-10 15:51:18 -0700560 ALOGI("Reconfiguring input devices, changes=%s",
561 InputReaderConfiguration::changesToString(changes).c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -0800562 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
563
564 if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) {
565 mEventHub->requestReopenDevices();
566 } else {
567 for (size_t i = 0; i < mDevices.size(); i++) {
568 InputDevice* device = mDevices.valueAt(i);
569 device->configure(now, &mConfig, changes);
570 }
571 }
572 }
573}
574
575void InputReader::updateGlobalMetaStateLocked() {
576 mGlobalMetaState = 0;
577
578 for (size_t i = 0; i < mDevices.size(); i++) {
579 InputDevice* device = mDevices.valueAt(i);
580 mGlobalMetaState |= device->getMetaState();
581 }
582}
583
584int32_t InputReader::getGlobalMetaStateLocked() {
585 return mGlobalMetaState;
586}
587
Michael Wright842500e2015-03-13 17:32:02 -0700588void InputReader::notifyExternalStylusPresenceChanged() {
589 refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE);
590}
591
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800592void InputReader::getExternalStylusDevicesLocked(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700593 for (size_t i = 0; i < mDevices.size(); i++) {
594 InputDevice* device = mDevices.valueAt(i);
595 if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800596 InputDeviceInfo info;
597 device->getDeviceInfo(&info);
598 outDevices.push_back(info);
Michael Wright842500e2015-03-13 17:32:02 -0700599 }
600 }
601}
602
603void InputReader::dispatchExternalStylusState(const StylusState& state) {
604 for (size_t i = 0; i < mDevices.size(); i++) {
605 InputDevice* device = mDevices.valueAt(i);
606 device->updateExternalStylusState(state);
607 }
608}
609
Michael Wrightd02c5b62014-02-10 15:10:22 -0800610void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) {
611 mDisableVirtualKeysTimeout = time;
612}
613
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700614bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, InputDevice* device, int32_t keyCode,
615 int32_t scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800616 if (now < mDisableVirtualKeysTimeout) {
617 ALOGI("Dropping virtual key from device %s because virtual keys are "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700618 "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d",
619 device->getName().c_str(), (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode,
620 scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800621 return true;
622 } else {
623 return false;
624 }
625}
626
627void InputReader::fadePointerLocked() {
628 for (size_t i = 0; i < mDevices.size(); i++) {
629 InputDevice* device = mDevices.valueAt(i);
630 device->fadePointer();
631 }
632}
633
634void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) {
635 if (when < mNextTimeout) {
636 mNextTimeout = when;
637 mEventHub->wake();
638 }
639}
640
641int32_t InputReader::bumpGenerationLocked() {
642 return ++mGeneration;
643}
644
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800645void InputReader::getInputDevices(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800646 AutoMutex _l(mLock);
647 getInputDevicesLocked(outInputDevices);
648}
649
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800650void InputReader::getInputDevicesLocked(std::vector<InputDeviceInfo>& outInputDevices) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800651 outInputDevices.clear();
652
653 size_t numDevices = mDevices.size();
654 for (size_t i = 0; i < numDevices; i++) {
655 InputDevice* device = mDevices.valueAt(i);
656 if (!device->isIgnored()) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800657 InputDeviceInfo info;
658 device->getDeviceInfo(&info);
659 outInputDevices.push_back(info);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800660 }
661 }
662}
663
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700664int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800665 AutoMutex _l(mLock);
666
667 return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState);
668}
669
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700670int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800671 AutoMutex _l(mLock);
672
673 return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState);
674}
675
676int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) {
677 AutoMutex _l(mLock);
678
679 return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState);
680}
681
682int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700683 GetStateFunc getStateFunc) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800684 int32_t result = AKEY_STATE_UNKNOWN;
685 if (deviceId >= 0) {
686 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
687 if (deviceIndex >= 0) {
688 InputDevice* device = mDevices.valueAt(deviceIndex);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700689 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800690 result = (device->*getStateFunc)(sourceMask, code);
691 }
692 }
693 } else {
694 size_t numDevices = mDevices.size();
695 for (size_t i = 0; i < numDevices; i++) {
696 InputDevice* device = mDevices.valueAt(i);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700697 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800698 // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
699 // value. Otherwise, return AKEY_STATE_UP as long as one device reports it.
700 int32_t currentResult = (device->*getStateFunc)(sourceMask, code);
701 if (currentResult >= AKEY_STATE_DOWN) {
702 return currentResult;
703 } else if (currentResult == AKEY_STATE_UP) {
704 result = currentResult;
705 }
706 }
707 }
708 }
709 return result;
710}
711
Andrii Kulian763a3a42016-03-08 10:46:16 -0800712void InputReader::toggleCapsLockState(int32_t deviceId) {
713 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
714 if (deviceIndex < 0) {
715 ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId);
716 return;
717 }
718
719 InputDevice* device = mDevices.valueAt(deviceIndex);
720 if (device->isIgnored()) {
721 return;
722 }
723
724 device->updateMetaState(AKEYCODE_CAPS_LOCK);
725}
726
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700727bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes,
728 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800729 AutoMutex _l(mLock);
730
731 memset(outFlags, 0, numCodes);
732 return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags);
733}
734
735bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700736 size_t numCodes, const int32_t* keyCodes,
737 uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800738 bool result = false;
739 if (deviceId >= 0) {
740 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
741 if (deviceIndex >= 0) {
742 InputDevice* device = mDevices.valueAt(deviceIndex);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700743 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
744 result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800745 }
746 }
747 } else {
748 size_t numDevices = mDevices.size();
749 for (size_t i = 0; i < numDevices; i++) {
750 InputDevice* device = mDevices.valueAt(i);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700751 if (!device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) {
752 result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800753 }
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,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700773 ssize_t repeat, int32_t token) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800774 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
Arthur Hungc23540e2018-11-29 20:42:11 +0800805bool InputReader::canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
806 AutoMutex _l(mLock);
807
808 ssize_t deviceIndex = mDevices.indexOfKey(deviceId);
809 if (deviceIndex < 0) {
810 ALOGW("Ignoring invalid device id %" PRId32 ".", deviceId);
811 return false;
812 }
813
814 InputDevice* device = mDevices.valueAt(deviceIndex);
Arthur Hung2c9a3342019-07-23 14:18:59 +0800815 if (!device->isEnabled()) {
816 ALOGW("Ignoring disabled device %s", device->getName().c_str());
817 return false;
818 }
819
820 std::optional<int32_t> associatedDisplayId = device->getAssociatedDisplayId();
Arthur Hungc23540e2018-11-29 20:42:11 +0800821 // No associated display. By default, can dispatch to all displays.
822 if (!associatedDisplayId) {
823 return true;
824 }
825
826 if (*associatedDisplayId == ADISPLAY_ID_NONE) {
Arthur Hung2c9a3342019-07-23 14:18:59 +0800827 ALOGW("Device %s is associated with display ADISPLAY_ID_NONE.", device->getName().c_str());
Arthur Hungc23540e2018-11-29 20:42:11 +0800828 return true;
829 }
830
831 return *associatedDisplayId == displayId;
832}
833
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800834void InputReader::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800835 AutoMutex _l(mLock);
836
837 mEventHub->dump(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800838 dump += "\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800839
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800840 dump += "Input Reader State:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800841
842 for (size_t i = 0; i < mDevices.size(); i++) {
843 mDevices.valueAt(i)->dump(dump);
844 }
845
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800846 dump += INDENT "Configuration:\n";
847 dump += INDENT2 "ExcludedDeviceNames: [";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800848 for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) {
849 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800850 dump += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -0800851 }
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +0100852 dump += mConfig.excludedDeviceNames[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -0800853 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800854 dump += "]\n";
855 dump += StringPrintf(INDENT2 "VirtualKeyQuietTime: %0.1fms\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700856 mConfig.virtualKeyQuietTime * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800857
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800858 dump += StringPrintf(INDENT2 "PointerVelocityControlParameters: "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700859 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
860 "acceleration=%0.3f\n",
861 mConfig.pointerVelocityControlParameters.scale,
862 mConfig.pointerVelocityControlParameters.lowThreshold,
863 mConfig.pointerVelocityControlParameters.highThreshold,
864 mConfig.pointerVelocityControlParameters.acceleration);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800865
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800866 dump += StringPrintf(INDENT2 "WheelVelocityControlParameters: "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700867 "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, "
868 "acceleration=%0.3f\n",
869 mConfig.wheelVelocityControlParameters.scale,
870 mConfig.wheelVelocityControlParameters.lowThreshold,
871 mConfig.wheelVelocityControlParameters.highThreshold,
872 mConfig.wheelVelocityControlParameters.acceleration);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800873
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800874 dump += StringPrintf(INDENT2 "PointerGesture:\n");
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700875 dump += StringPrintf(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800876 dump += StringPrintf(INDENT3 "QuietInterval: %0.1fms\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700877 mConfig.pointerGestureQuietInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800878 dump += StringPrintf(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700879 mConfig.pointerGestureDragMinSwitchSpeed);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800880 dump += StringPrintf(INDENT3 "TapInterval: %0.1fms\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700881 mConfig.pointerGestureTapInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800882 dump += StringPrintf(INDENT3 "TapDragInterval: %0.1fms\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700883 mConfig.pointerGestureTapDragInterval * 0.000001f);
884 dump += StringPrintf(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800885 dump += StringPrintf(INDENT3 "MultitouchSettleInterval: %0.1fms\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700886 mConfig.pointerGestureMultitouchSettleInterval * 0.000001f);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800887 dump += StringPrintf(INDENT3 "MultitouchMinDistance: %0.1fpx\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700888 mConfig.pointerGestureMultitouchMinDistance);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800889 dump += StringPrintf(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700890 mConfig.pointerGestureSwipeTransitionAngleCosine);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800891 dump += StringPrintf(INDENT3 "SwipeMaxWidthRatio: %0.1f\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700892 mConfig.pointerGestureSwipeMaxWidthRatio);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800893 dump += StringPrintf(INDENT3 "MovementSpeedRatio: %0.1f\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700894 mConfig.pointerGestureMovementSpeedRatio);
895 dump += StringPrintf(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio);
Santos Cordonfa5cf462017-04-05 10:37:00 -0700896
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800897 dump += INDENT3 "Viewports:\n";
Santos Cordonfa5cf462017-04-05 10:37:00 -0700898 mConfig.dump(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -0800899}
900
901void InputReader::monitor() {
902 // Acquire and release the lock to ensure that the reader has not deadlocked.
903 mLock.lock();
904 mEventHub->wake();
905 mReaderIsAliveCondition.wait(mLock);
906 mLock.unlock();
907
908 // Check the EventHub
909 mEventHub->monitor();
910}
911
Michael Wrightd02c5b62014-02-10 15:10:22 -0800912// --- InputReader::ContextImpl ---
913
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700914InputReader::ContextImpl::ContextImpl(InputReader* reader) : mReader(reader) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800915
916void InputReader::ContextImpl::updateGlobalMetaState() {
917 // lock is already held by the input loop
918 mReader->updateGlobalMetaStateLocked();
919}
920
921int32_t InputReader::ContextImpl::getGlobalMetaState() {
922 // lock is already held by the input loop
923 return mReader->getGlobalMetaStateLocked();
924}
925
926void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) {
927 // lock is already held by the input loop
928 mReader->disableVirtualKeysUntilLocked(time);
929}
930
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700931bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, InputDevice* device,
932 int32_t keyCode, int32_t scanCode) {
Michael Wrightd02c5b62014-02-10 15:10:22 -0800933 // lock is already held by the input loop
934 return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode);
935}
936
937void InputReader::ContextImpl::fadePointer() {
938 // lock is already held by the input loop
939 mReader->fadePointerLocked();
940}
941
942void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) {
943 // lock is already held by the input loop
944 mReader->requestTimeoutAtTimeLocked(when);
945}
946
947int32_t InputReader::ContextImpl::bumpGeneration() {
948 // lock is already held by the input loop
949 return mReader->bumpGenerationLocked();
950}
951
Arthur Hung7c3ae9c2019-03-11 11:23:03 +0800952void InputReader::ContextImpl::getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) {
Michael Wright842500e2015-03-13 17:32:02 -0700953 // lock is already held by whatever called refreshConfigurationLocked
954 mReader->getExternalStylusDevicesLocked(outDevices);
955}
956
957void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) {
958 mReader->dispatchExternalStylusState(state);
959}
960
Michael Wrightd02c5b62014-02-10 15:10:22 -0800961InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() {
962 return mReader->mPolicy.get();
963}
964
965InputListenerInterface* InputReader::ContextImpl::getListener() {
966 return mReader->mQueuedListener.get();
967}
968
969EventHubInterface* InputReader::ContextImpl::getEventHub() {
970 return mReader->mEventHub.get();
971}
972
Prabir Pradhan42611e02018-11-27 14:04:02 -0800973uint32_t InputReader::ContextImpl::getNextSequenceNum() {
974 return (mReader->mNextSequenceNum)++;
975}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800976
Michael Wrightd02c5b62014-02-10 15:10:22 -0800977// --- InputDevice ---
978
979InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -0700980 int32_t controllerNumber, const InputDeviceIdentifier& identifier,
981 uint32_t classes)
982 : mContext(context),
983 mId(id),
984 mGeneration(generation),
985 mControllerNumber(controllerNumber),
986 mIdentifier(identifier),
987 mClasses(classes),
988 mSources(0),
989 mIsExternal(false),
990 mHasMic(false),
991 mDropUntilNextSync(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -0800992
993InputDevice::~InputDevice() {
994 size_t numMappers = mMappers.size();
995 for (size_t i = 0; i < numMappers; i++) {
996 delete mMappers[i];
997 }
998 mMappers.clear();
999}
1000
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001001bool InputDevice::isEnabled() {
1002 return getEventHub()->isDeviceEnabled(mId);
1003}
1004
1005void InputDevice::setEnabled(bool enabled, nsecs_t when) {
Arthur Hung2c9a3342019-07-23 14:18:59 +08001006 if (enabled && mAssociatedDisplayPort && !mAssociatedViewport) {
1007 ALOGW("Cannot enable input device %s because it is associated with port %" PRIu8 ", "
1008 "but the corresponding viewport is not found",
1009 getName().c_str(), *mAssociatedDisplayPort);
1010 enabled = false;
1011 }
1012
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001013 if (isEnabled() == enabled) {
1014 return;
1015 }
1016
1017 if (enabled) {
1018 getEventHub()->enableDevice(mId);
1019 reset(when);
1020 } else {
1021 reset(when);
1022 getEventHub()->disableDevice(mId);
1023 }
1024 // Must change generation to flag this device as changed
1025 bumpGeneration();
1026}
1027
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001028void InputDevice::dump(std::string& dump) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001029 InputDeviceInfo deviceInfo;
Siarhei Vishniakoucd7ac1e2018-10-15 13:39:50 -07001030 getDeviceInfo(&deviceInfo);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001031
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001032 dump += StringPrintf(INDENT "Device %d: %s\n", deviceInfo.getId(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001033 deviceInfo.getDisplayName().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001034 dump += StringPrintf(INDENT2 "Generation: %d\n", mGeneration);
1035 dump += StringPrintf(INDENT2 "IsExternal: %s\n", toString(mIsExternal));
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001036 dump += StringPrintf(INDENT2 "AssociatedDisplayPort: ");
1037 if (mAssociatedDisplayPort) {
1038 dump += StringPrintf("%" PRIu8 "\n", *mAssociatedDisplayPort);
1039 } else {
1040 dump += "<none>\n";
1041 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001042 dump += StringPrintf(INDENT2 "HasMic: %s\n", toString(mHasMic));
1043 dump += StringPrintf(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources());
1044 dump += StringPrintf(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001045
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001046 const std::vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges();
1047 if (!ranges.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08001048 dump += INDENT2 "Motion Ranges:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08001049 for (size_t i = 0; i < ranges.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001050 const InputDeviceInfo::MotionRange& range = ranges[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08001051 const char* label = getAxisLabel(range.axis);
1052 char name[32];
1053 if (label) {
1054 strncpy(name, label, sizeof(name));
1055 name[sizeof(name) - 1] = '\0';
1056 } else {
1057 snprintf(name, sizeof(name), "%d", range.axis);
1058 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001059 dump += StringPrintf(INDENT3
1060 "%s: source=0x%08x, "
1061 "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n",
1062 name, range.source, range.min, range.max, range.flat, range.fuzz,
1063 range.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001064 }
1065 }
1066
1067 size_t numMappers = mMappers.size();
1068 for (size_t i = 0; i < numMappers; i++) {
1069 InputMapper* mapper = mMappers[i];
1070 mapper->dump(dump);
1071 }
1072}
1073
1074void InputDevice::addMapper(InputMapper* mapper) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001075 mMappers.push_back(mapper);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001076}
1077
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001078void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config,
1079 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001080 mSources = 0;
1081
1082 if (!isIgnored()) {
1083 if (!changes) { // first time only
1084 mContext->getEventHub()->getConfiguration(mId, &mConfiguration);
1085 }
1086
1087 if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
1088 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
1089 sp<KeyCharacterMap> keyboardLayout =
1090 mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier);
1091 if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) {
1092 bumpGeneration();
1093 }
1094 }
1095 }
1096
1097 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) {
1098 if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001099 std::string alias = mContext->getPolicy()->getDeviceAlias(mIdentifier);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001100 if (mAlias != alias) {
1101 mAlias = alias;
1102 bumpGeneration();
1103 }
1104 }
1105 }
1106
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001107 if (!changes || (changes & InputReaderConfiguration::CHANGE_ENABLED_STATE)) {
Siarhei Vishniakouc6f61192019-07-23 18:12:31 +00001108 auto it = config->disabledDevices.find(mId);
1109 bool enabled = it == config->disabledDevices.end();
Siarhei Vishniakoue54cb852017-03-21 17:48:16 -07001110 setEnabled(enabled, when);
1111 }
1112
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001113 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001114 // In most situations, no port will be specified.
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001115 mAssociatedDisplayPort = std::nullopt;
Arthur Hung2c9a3342019-07-23 14:18:59 +08001116 mAssociatedViewport = std::nullopt;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001117 // Find the display port that corresponds to the current input port.
1118 const std::string& inputPort = mIdentifier.location;
1119 if (!inputPort.empty()) {
1120 const std::unordered_map<std::string, uint8_t>& ports = config->portAssociations;
1121 const auto& displayPort = ports.find(inputPort);
1122 if (displayPort != ports.end()) {
1123 mAssociatedDisplayPort = std::make_optional(displayPort->second);
1124 }
1125 }
Arthur Hung2c9a3342019-07-23 14:18:59 +08001126
1127 // If the device was explicitly disabled by the user, it would be present in the
1128 // "disabledDevices" list. If it is associated with a specific display, and it was not
1129 // explicitly disabled, then enable/disable the device based on whether we can find the
1130 // corresponding viewport.
1131 bool enabled = (config->disabledDevices.find(mId) == config->disabledDevices.end());
1132 if (mAssociatedDisplayPort) {
1133 mAssociatedViewport = config->getDisplayViewportByPort(*mAssociatedDisplayPort);
1134 if (!mAssociatedViewport) {
1135 ALOGW("Input device %s should be associated with display on port %" PRIu8 ", "
1136 "but the corresponding viewport is not found.",
1137 getName().c_str(), *mAssociatedDisplayPort);
1138 enabled = false;
1139 }
1140 }
1141
Arthur Hung9da14732019-09-02 16:16:58 +08001142 if (changes) {
1143 // For first-time configuration, only allow device to be disabled after mappers have
1144 // finished configuring. This is because we need to read some of the properties from
1145 // the device's open fd.
1146 setEnabled(enabled, when);
1147 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07001148 }
1149
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001150 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001151 mapper->configure(when, config, changes);
1152 mSources |= mapper->getSources();
1153 }
Arthur Hung9da14732019-09-02 16:16:58 +08001154
1155 // If a device is just plugged but it might be disabled, we need to update some info like
1156 // axis range of touch from each InputMapper first, then disable it.
1157 if (!changes) {
1158 setEnabled(config->disabledDevices.find(mId) == config->disabledDevices.end(), when);
1159 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08001160 }
1161}
1162
1163void InputDevice::reset(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001164 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001165 mapper->reset(when);
1166 }
1167
1168 mContext->updateGlobalMetaState();
1169
1170 notifyReset(when);
1171}
1172
1173void InputDevice::process(const RawEvent* rawEvents, size_t count) {
1174 // Process all of the events in order for each mapper.
1175 // We cannot simply ask each mapper to process them in bulk because mappers may
1176 // have side-effects that must be interleaved. For example, joystick movement events and
1177 // gamepad button presses are handled by different mappers but they should be dispatched
1178 // in the order received.
Ivan Lozano96f12992017-11-09 14:45:38 -08001179 for (const RawEvent* rawEvent = rawEvents; count != 0; rawEvent++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001180#if DEBUG_RAW_EVENTS
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07001181 ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%" PRId64,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001182 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value, rawEvent->when);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001183#endif
1184
1185 if (mDropUntilNextSync) {
1186 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1187 mDropUntilNextSync = false;
1188#if DEBUG_RAW_EVENTS
1189 ALOGD("Recovered from input event buffer overrun.");
1190#endif
1191 } else {
1192#if DEBUG_RAW_EVENTS
1193 ALOGD("Dropped input event while waiting for next input sync.");
1194#endif
1195 }
1196 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01001197 ALOGI("Detected input event buffer overrun for device %s.", getName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08001198 mDropUntilNextSync = true;
1199 reset(rawEvent->when);
1200 } else {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001201 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001202 mapper->process(rawEvent);
1203 }
1204 }
Ivan Lozano96f12992017-11-09 14:45:38 -08001205 --count;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001206 }
1207}
1208
1209void InputDevice::timeoutExpired(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001210 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001211 mapper->timeoutExpired(when);
1212 }
1213}
1214
Michael Wright842500e2015-03-13 17:32:02 -07001215void InputDevice::updateExternalStylusState(const StylusState& state) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001216 for (InputMapper* mapper : mMappers) {
Michael Wright842500e2015-03-13 17:32:02 -07001217 mapper->updateExternalStylusState(state);
1218 }
1219}
1220
Michael Wrightd02c5b62014-02-10 15:10:22 -08001221void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001222 outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
1223 mHasMic);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001224 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001225 mapper->populateDeviceInfo(outDeviceInfo);
1226 }
1227}
1228
1229int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001230 return getState(sourceMask, keyCode, &InputMapper::getKeyCodeState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001231}
1232
1233int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001234 return getState(sourceMask, scanCode, &InputMapper::getScanCodeState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001235}
1236
1237int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001238 return getState(sourceMask, switchCode, &InputMapper::getSwitchState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001239}
1240
1241int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) {
1242 int32_t result = AKEY_STATE_UNKNOWN;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001243 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001244 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1245 // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that
1246 // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it.
1247 int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code);
1248 if (currentResult >= AKEY_STATE_DOWN) {
1249 return currentResult;
1250 } else if (currentResult == AKEY_STATE_UP) {
1251 result = currentResult;
1252 }
1253 }
1254 }
1255 return result;
1256}
1257
1258bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001259 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001260 bool result = false;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001261 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001262 if (sourcesMatchMask(mapper->getSources(), sourceMask)) {
1263 result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags);
1264 }
1265 }
1266 return result;
1267}
1268
1269void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001270 int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001271 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001272 mapper->vibrate(pattern, patternSize, repeat, token);
1273 }
1274}
1275
1276void InputDevice::cancelVibrate(int32_t token) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001277 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001278 mapper->cancelVibrate(token);
1279 }
1280}
1281
Jeff Brownc9aa6282015-02-11 19:03:28 -08001282void InputDevice::cancelTouch(nsecs_t when) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001283 for (InputMapper* mapper : mMappers) {
Jeff Brownc9aa6282015-02-11 19:03:28 -08001284 mapper->cancelTouch(when);
1285 }
1286}
1287
Michael Wrightd02c5b62014-02-10 15:10:22 -08001288int32_t InputDevice::getMetaState() {
1289 int32_t result = 0;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001290 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001291 result |= mapper->getMetaState();
1292 }
1293 return result;
1294}
1295
Andrii Kulian763a3a42016-03-08 10:46:16 -08001296void InputDevice::updateMetaState(int32_t keyCode) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001297 for (InputMapper* mapper : mMappers) {
1298 mapper->updateMetaState(keyCode);
Andrii Kulian763a3a42016-03-08 10:46:16 -08001299 }
1300}
1301
Michael Wrightd02c5b62014-02-10 15:10:22 -08001302void InputDevice::fadePointer() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001303 for (InputMapper* mapper : mMappers) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001304 mapper->fadePointer();
1305 }
1306}
1307
1308void InputDevice::bumpGeneration() {
1309 mGeneration = mContext->bumpGeneration();
1310}
1311
1312void InputDevice::notifyReset(nsecs_t when) {
Prabir Pradhan42611e02018-11-27 14:04:02 -08001313 NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001314 mContext->getListener()->notifyDeviceReset(&args);
1315}
1316
Arthur Hung2c9a3342019-07-23 14:18:59 +08001317std::optional<int32_t> InputDevice::getAssociatedDisplayId() {
1318 // Check if we had associated to the specific display.
1319 if (mAssociatedViewport) {
1320 return mAssociatedViewport->displayId;
1321 }
1322
1323 // No associated display port, check if some InputMapper is associated.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08001324 for (InputMapper* mapper : mMappers) {
Arthur Hung2c9a3342019-07-23 14:18:59 +08001325 std::optional<int32_t> associatedDisplayId = mapper->getAssociatedDisplayId();
Arthur Hungc23540e2018-11-29 20:42:11 +08001326 if (associatedDisplayId) {
1327 return associatedDisplayId;
1328 }
1329 }
1330
1331 return std::nullopt;
1332}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001333
1334// --- CursorButtonAccumulator ---
1335
1336CursorButtonAccumulator::CursorButtonAccumulator() {
1337 clearButtons();
1338}
1339
1340void CursorButtonAccumulator::reset(InputDevice* device) {
1341 mBtnLeft = device->isKeyPressed(BTN_LEFT);
1342 mBtnRight = device->isKeyPressed(BTN_RIGHT);
1343 mBtnMiddle = device->isKeyPressed(BTN_MIDDLE);
1344 mBtnBack = device->isKeyPressed(BTN_BACK);
1345 mBtnSide = device->isKeyPressed(BTN_SIDE);
1346 mBtnForward = device->isKeyPressed(BTN_FORWARD);
1347 mBtnExtra = device->isKeyPressed(BTN_EXTRA);
1348 mBtnTask = device->isKeyPressed(BTN_TASK);
1349}
1350
1351void CursorButtonAccumulator::clearButtons() {
1352 mBtnLeft = 0;
1353 mBtnRight = 0;
1354 mBtnMiddle = 0;
1355 mBtnBack = 0;
1356 mBtnSide = 0;
1357 mBtnForward = 0;
1358 mBtnExtra = 0;
1359 mBtnTask = 0;
1360}
1361
1362void CursorButtonAccumulator::process(const RawEvent* rawEvent) {
1363 if (rawEvent->type == EV_KEY) {
1364 switch (rawEvent->code) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001365 case BTN_LEFT:
1366 mBtnLeft = rawEvent->value;
1367 break;
1368 case BTN_RIGHT:
1369 mBtnRight = rawEvent->value;
1370 break;
1371 case BTN_MIDDLE:
1372 mBtnMiddle = rawEvent->value;
1373 break;
1374 case BTN_BACK:
1375 mBtnBack = rawEvent->value;
1376 break;
1377 case BTN_SIDE:
1378 mBtnSide = rawEvent->value;
1379 break;
1380 case BTN_FORWARD:
1381 mBtnForward = rawEvent->value;
1382 break;
1383 case BTN_EXTRA:
1384 mBtnExtra = rawEvent->value;
1385 break;
1386 case BTN_TASK:
1387 mBtnTask = rawEvent->value;
1388 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001389 }
1390 }
1391}
1392
1393uint32_t CursorButtonAccumulator::getButtonState() const {
1394 uint32_t result = 0;
1395 if (mBtnLeft) {
1396 result |= AMOTION_EVENT_BUTTON_PRIMARY;
1397 }
1398 if (mBtnRight) {
1399 result |= AMOTION_EVENT_BUTTON_SECONDARY;
1400 }
1401 if (mBtnMiddle) {
1402 result |= AMOTION_EVENT_BUTTON_TERTIARY;
1403 }
1404 if (mBtnBack || mBtnSide) {
1405 result |= AMOTION_EVENT_BUTTON_BACK;
1406 }
1407 if (mBtnForward || mBtnExtra) {
1408 result |= AMOTION_EVENT_BUTTON_FORWARD;
1409 }
1410 return result;
1411}
1412
Michael Wrightd02c5b62014-02-10 15:10:22 -08001413// --- CursorMotionAccumulator ---
1414
1415CursorMotionAccumulator::CursorMotionAccumulator() {
1416 clearRelativeAxes();
1417}
1418
1419void CursorMotionAccumulator::reset(InputDevice* device) {
1420 clearRelativeAxes();
1421}
1422
1423void CursorMotionAccumulator::clearRelativeAxes() {
1424 mRelX = 0;
1425 mRelY = 0;
1426}
1427
1428void CursorMotionAccumulator::process(const RawEvent* rawEvent) {
1429 if (rawEvent->type == EV_REL) {
1430 switch (rawEvent->code) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001431 case REL_X:
1432 mRelX = rawEvent->value;
1433 break;
1434 case REL_Y:
1435 mRelY = rawEvent->value;
1436 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001437 }
1438 }
1439}
1440
1441void CursorMotionAccumulator::finishSync() {
1442 clearRelativeAxes();
1443}
1444
Michael Wrightd02c5b62014-02-10 15:10:22 -08001445// --- CursorScrollAccumulator ---
1446
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001447CursorScrollAccumulator::CursorScrollAccumulator() : mHaveRelWheel(false), mHaveRelHWheel(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001448 clearRelativeAxes();
1449}
1450
1451void CursorScrollAccumulator::configure(InputDevice* device) {
1452 mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL);
1453 mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL);
1454}
1455
1456void CursorScrollAccumulator::reset(InputDevice* device) {
1457 clearRelativeAxes();
1458}
1459
1460void CursorScrollAccumulator::clearRelativeAxes() {
1461 mRelWheel = 0;
1462 mRelHWheel = 0;
1463}
1464
1465void CursorScrollAccumulator::process(const RawEvent* rawEvent) {
1466 if (rawEvent->type == EV_REL) {
1467 switch (rawEvent->code) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001468 case REL_WHEEL:
1469 mRelWheel = rawEvent->value;
1470 break;
1471 case REL_HWHEEL:
1472 mRelHWheel = rawEvent->value;
1473 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001474 }
1475 }
1476}
1477
1478void CursorScrollAccumulator::finishSync() {
1479 clearRelativeAxes();
1480}
1481
Michael Wrightd02c5b62014-02-10 15:10:22 -08001482// --- TouchButtonAccumulator ---
1483
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001484TouchButtonAccumulator::TouchButtonAccumulator() : mHaveBtnTouch(false), mHaveStylus(false) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001485 clearButtons();
1486}
1487
1488void TouchButtonAccumulator::configure(InputDevice* device) {
1489 mHaveBtnTouch = device->hasKey(BTN_TOUCH);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001490 mHaveStylus = device->hasKey(BTN_TOOL_PEN) || device->hasKey(BTN_TOOL_RUBBER) ||
1491 device->hasKey(BTN_TOOL_BRUSH) || device->hasKey(BTN_TOOL_PENCIL) ||
1492 device->hasKey(BTN_TOOL_AIRBRUSH);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001493}
1494
1495void TouchButtonAccumulator::reset(InputDevice* device) {
1496 mBtnTouch = device->isKeyPressed(BTN_TOUCH);
1497 mBtnStylus = device->isKeyPressed(BTN_STYLUS);
Michael Wright842500e2015-03-13 17:32:02 -07001498 // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001499 mBtnStylus2 = device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001500 mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER);
1501 mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN);
1502 mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER);
1503 mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH);
1504 mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL);
1505 mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH);
1506 mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE);
1507 mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS);
1508 mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP);
1509 mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP);
1510 mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP);
1511}
1512
1513void TouchButtonAccumulator::clearButtons() {
1514 mBtnTouch = 0;
1515 mBtnStylus = 0;
1516 mBtnStylus2 = 0;
1517 mBtnToolFinger = 0;
1518 mBtnToolPen = 0;
1519 mBtnToolRubber = 0;
1520 mBtnToolBrush = 0;
1521 mBtnToolPencil = 0;
1522 mBtnToolAirbrush = 0;
1523 mBtnToolMouse = 0;
1524 mBtnToolLens = 0;
1525 mBtnToolDoubleTap = 0;
1526 mBtnToolTripleTap = 0;
1527 mBtnToolQuadTap = 0;
1528}
1529
1530void TouchButtonAccumulator::process(const RawEvent* rawEvent) {
1531 if (rawEvent->type == EV_KEY) {
1532 switch (rawEvent->code) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001533 case BTN_TOUCH:
1534 mBtnTouch = rawEvent->value;
1535 break;
1536 case BTN_STYLUS:
1537 mBtnStylus = rawEvent->value;
1538 break;
1539 case BTN_STYLUS2:
1540 case BTN_0: // BTN_0 is what gets mapped for the HID usage
1541 // Digitizers.SecondaryBarrelSwitch
1542 mBtnStylus2 = rawEvent->value;
1543 break;
1544 case BTN_TOOL_FINGER:
1545 mBtnToolFinger = rawEvent->value;
1546 break;
1547 case BTN_TOOL_PEN:
1548 mBtnToolPen = rawEvent->value;
1549 break;
1550 case BTN_TOOL_RUBBER:
1551 mBtnToolRubber = rawEvent->value;
1552 break;
1553 case BTN_TOOL_BRUSH:
1554 mBtnToolBrush = rawEvent->value;
1555 break;
1556 case BTN_TOOL_PENCIL:
1557 mBtnToolPencil = rawEvent->value;
1558 break;
1559 case BTN_TOOL_AIRBRUSH:
1560 mBtnToolAirbrush = rawEvent->value;
1561 break;
1562 case BTN_TOOL_MOUSE:
1563 mBtnToolMouse = rawEvent->value;
1564 break;
1565 case BTN_TOOL_LENS:
1566 mBtnToolLens = rawEvent->value;
1567 break;
1568 case BTN_TOOL_DOUBLETAP:
1569 mBtnToolDoubleTap = rawEvent->value;
1570 break;
1571 case BTN_TOOL_TRIPLETAP:
1572 mBtnToolTripleTap = rawEvent->value;
1573 break;
1574 case BTN_TOOL_QUADTAP:
1575 mBtnToolQuadTap = rawEvent->value;
1576 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001577 }
1578 }
1579}
1580
1581uint32_t TouchButtonAccumulator::getButtonState() const {
1582 uint32_t result = 0;
1583 if (mBtnStylus) {
Michael Wright7b159c92015-05-14 14:48:03 +01001584 result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001585 }
1586 if (mBtnStylus2) {
Michael Wright7b159c92015-05-14 14:48:03 +01001587 result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001588 }
1589 return result;
1590}
1591
1592int32_t TouchButtonAccumulator::getToolType() const {
1593 if (mBtnToolMouse || mBtnToolLens) {
1594 return AMOTION_EVENT_TOOL_TYPE_MOUSE;
1595 }
1596 if (mBtnToolRubber) {
1597 return AMOTION_EVENT_TOOL_TYPE_ERASER;
1598 }
1599 if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) {
1600 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
1601 }
1602 if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) {
1603 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1604 }
1605 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1606}
1607
1608bool TouchButtonAccumulator::isToolActive() const {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001609 return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber || mBtnToolBrush ||
1610 mBtnToolPencil || mBtnToolAirbrush || mBtnToolMouse || mBtnToolLens ||
1611 mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001612}
1613
1614bool TouchButtonAccumulator::isHovering() const {
1615 return mHaveBtnTouch && !mBtnTouch;
1616}
1617
1618bool TouchButtonAccumulator::hasStylus() const {
1619 return mHaveStylus;
1620}
1621
Michael Wrightd02c5b62014-02-10 15:10:22 -08001622// --- RawPointerAxes ---
1623
1624RawPointerAxes::RawPointerAxes() {
1625 clear();
1626}
1627
1628void RawPointerAxes::clear() {
1629 x.clear();
1630 y.clear();
1631 pressure.clear();
1632 touchMajor.clear();
1633 touchMinor.clear();
1634 toolMajor.clear();
1635 toolMinor.clear();
1636 orientation.clear();
1637 distance.clear();
1638 tiltX.clear();
1639 tiltY.clear();
1640 trackingId.clear();
1641 slot.clear();
1642}
1643
Michael Wrightd02c5b62014-02-10 15:10:22 -08001644// --- RawPointerData ---
1645
1646RawPointerData::RawPointerData() {
1647 clear();
1648}
1649
1650void RawPointerData::clear() {
1651 pointerCount = 0;
1652 clearIdBits();
1653}
1654
1655void RawPointerData::copyFrom(const RawPointerData& other) {
1656 pointerCount = other.pointerCount;
1657 hoveringIdBits = other.hoveringIdBits;
1658 touchingIdBits = other.touchingIdBits;
1659
1660 for (uint32_t i = 0; i < pointerCount; i++) {
1661 pointers[i] = other.pointers[i];
1662
1663 int id = pointers[i].id;
1664 idToIndex[id] = other.idToIndex[id];
1665 }
1666}
1667
1668void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
1669 float x = 0, y = 0;
1670 uint32_t count = touchingIdBits.count();
1671 if (count) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001672 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001673 uint32_t id = idBits.clearFirstMarkedBit();
1674 const Pointer& pointer = pointerForId(id);
1675 x += pointer.x;
1676 y += pointer.y;
1677 }
1678 x /= count;
1679 y /= count;
1680 }
1681 *outX = x;
1682 *outY = y;
1683}
1684
Michael Wrightd02c5b62014-02-10 15:10:22 -08001685// --- CookedPointerData ---
1686
1687CookedPointerData::CookedPointerData() {
1688 clear();
1689}
1690
1691void CookedPointerData::clear() {
1692 pointerCount = 0;
1693 hoveringIdBits.clear();
1694 touchingIdBits.clear();
1695}
1696
1697void CookedPointerData::copyFrom(const CookedPointerData& other) {
1698 pointerCount = other.pointerCount;
1699 hoveringIdBits = other.hoveringIdBits;
1700 touchingIdBits = other.touchingIdBits;
1701
1702 for (uint32_t i = 0; i < pointerCount; i++) {
1703 pointerProperties[i].copyFrom(other.pointerProperties[i]);
1704 pointerCoords[i].copyFrom(other.pointerCoords[i]);
1705
1706 int id = pointerProperties[i].id;
1707 idToIndex[id] = other.idToIndex[id];
1708 }
1709}
1710
Michael Wrightd02c5b62014-02-10 15:10:22 -08001711// --- SingleTouchMotionAccumulator ---
1712
1713SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() {
1714 clearAbsoluteAxes();
1715}
1716
1717void SingleTouchMotionAccumulator::reset(InputDevice* device) {
1718 mAbsX = device->getAbsoluteAxisValue(ABS_X);
1719 mAbsY = device->getAbsoluteAxisValue(ABS_Y);
1720 mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE);
1721 mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH);
1722 mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE);
1723 mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X);
1724 mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y);
1725}
1726
1727void SingleTouchMotionAccumulator::clearAbsoluteAxes() {
1728 mAbsX = 0;
1729 mAbsY = 0;
1730 mAbsPressure = 0;
1731 mAbsToolWidth = 0;
1732 mAbsDistance = 0;
1733 mAbsTiltX = 0;
1734 mAbsTiltY = 0;
1735}
1736
1737void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1738 if (rawEvent->type == EV_ABS) {
1739 switch (rawEvent->code) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001740 case ABS_X:
1741 mAbsX = rawEvent->value;
1742 break;
1743 case ABS_Y:
1744 mAbsY = rawEvent->value;
1745 break;
1746 case ABS_PRESSURE:
1747 mAbsPressure = rawEvent->value;
1748 break;
1749 case ABS_TOOL_WIDTH:
1750 mAbsToolWidth = rawEvent->value;
1751 break;
1752 case ABS_DISTANCE:
1753 mAbsDistance = rawEvent->value;
1754 break;
1755 case ABS_TILT_X:
1756 mAbsTiltX = rawEvent->value;
1757 break;
1758 case ABS_TILT_Y:
1759 mAbsTiltY = rawEvent->value;
1760 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001761 }
1762 }
1763}
1764
Michael Wrightd02c5b62014-02-10 15:10:22 -08001765// --- MultiTouchMotionAccumulator ---
1766
Atif Niyaz21da0ff2019-06-28 13:22:51 -07001767MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
1768 : mCurrentSlot(-1),
1769 mSlots(nullptr),
1770 mSlotCount(0),
1771 mUsingSlotsProtocol(false),
1772 mHaveStylus(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001773
1774MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() {
1775 delete[] mSlots;
1776}
1777
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001778void MultiTouchMotionAccumulator::configure(InputDevice* device, size_t slotCount,
1779 bool usingSlotsProtocol) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001780 mSlotCount = slotCount;
1781 mUsingSlotsProtocol = usingSlotsProtocol;
1782 mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE);
1783
1784 delete[] mSlots;
1785 mSlots = new Slot[slotCount];
1786}
1787
1788void MultiTouchMotionAccumulator::reset(InputDevice* device) {
1789 // Unfortunately there is no way to read the initial contents of the slots.
1790 // So when we reset the accumulator, we must assume they are all zeroes.
1791 if (mUsingSlotsProtocol) {
1792 // Query the driver for the current slot index and use it as the initial slot
1793 // before we start reading events from the device. It is possible that the
1794 // current slot index will not be the same as it was when the first event was
1795 // written into the evdev buffer, which means the input mapper could start
1796 // out of sync with the initial state of the events in the evdev buffer.
1797 // In the extremely unlikely case that this happens, the data from
1798 // two slots will be confused until the next ABS_MT_SLOT event is received.
1799 // This can cause the touch point to "jump", but at least there will be
1800 // no stuck touches.
1801 int32_t initialSlot;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001802 status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(), ABS_MT_SLOT,
1803 &initialSlot);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001804 if (status) {
1805 ALOGD("Could not retrieve current multitouch slot index. status=%d", status);
1806 initialSlot = -1;
1807 }
1808 clearSlots(initialSlot);
1809 } else {
1810 clearSlots(-1);
1811 }
1812}
1813
1814void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) {
1815 if (mSlots) {
1816 for (size_t i = 0; i < mSlotCount; i++) {
1817 mSlots[i].clear();
1818 }
1819 }
1820 mCurrentSlot = initialSlot;
1821}
1822
1823void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) {
1824 if (rawEvent->type == EV_ABS) {
1825 bool newSlot = false;
1826 if (mUsingSlotsProtocol) {
1827 if (rawEvent->code == ABS_MT_SLOT) {
1828 mCurrentSlot = rawEvent->value;
1829 newSlot = true;
1830 }
1831 } else if (mCurrentSlot < 0) {
1832 mCurrentSlot = 0;
1833 }
1834
1835 if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) {
1836#if DEBUG_POINTERS
1837 if (newSlot) {
1838 ALOGW("MultiTouch device emitted invalid slot index %d but it "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001839 "should be between 0 and %zd; ignoring this slot.",
1840 mCurrentSlot, mSlotCount - 1);
Michael Wrightd02c5b62014-02-10 15:10:22 -08001841 }
1842#endif
1843 } else {
1844 Slot* slot = &mSlots[mCurrentSlot];
1845
1846 switch (rawEvent->code) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001847 case ABS_MT_POSITION_X:
Michael Wrightd02c5b62014-02-10 15:10:22 -08001848 slot->mInUse = true;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001849 slot->mAbsMTPositionX = rawEvent->value;
1850 break;
1851 case ABS_MT_POSITION_Y:
1852 slot->mInUse = true;
1853 slot->mAbsMTPositionY = rawEvent->value;
1854 break;
1855 case ABS_MT_TOUCH_MAJOR:
1856 slot->mInUse = true;
1857 slot->mAbsMTTouchMajor = rawEvent->value;
1858 break;
1859 case ABS_MT_TOUCH_MINOR:
1860 slot->mInUse = true;
1861 slot->mAbsMTTouchMinor = rawEvent->value;
1862 slot->mHaveAbsMTTouchMinor = true;
1863 break;
1864 case ABS_MT_WIDTH_MAJOR:
1865 slot->mInUse = true;
1866 slot->mAbsMTWidthMajor = rawEvent->value;
1867 break;
1868 case ABS_MT_WIDTH_MINOR:
1869 slot->mInUse = true;
1870 slot->mAbsMTWidthMinor = rawEvent->value;
1871 slot->mHaveAbsMTWidthMinor = true;
1872 break;
1873 case ABS_MT_ORIENTATION:
1874 slot->mInUse = true;
1875 slot->mAbsMTOrientation = rawEvent->value;
1876 break;
1877 case ABS_MT_TRACKING_ID:
1878 if (mUsingSlotsProtocol && rawEvent->value < 0) {
1879 // The slot is no longer in use but it retains its previous contents,
1880 // which may be reused for subsequent touches.
1881 slot->mInUse = false;
1882 } else {
1883 slot->mInUse = true;
1884 slot->mAbsMTTrackingId = rawEvent->value;
1885 }
1886 break;
1887 case ABS_MT_PRESSURE:
1888 slot->mInUse = true;
1889 slot->mAbsMTPressure = rawEvent->value;
1890 break;
1891 case ABS_MT_DISTANCE:
1892 slot->mInUse = true;
1893 slot->mAbsMTDistance = rawEvent->value;
1894 break;
1895 case ABS_MT_TOOL_TYPE:
1896 slot->mInUse = true;
1897 slot->mAbsMTToolType = rawEvent->value;
1898 slot->mHaveAbsMTToolType = true;
1899 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001900 }
1901 }
1902 } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) {
1903 // MultiTouch Sync: The driver has returned all data for *one* of the pointers.
1904 mCurrentSlot += 1;
1905 }
1906}
1907
1908void MultiTouchMotionAccumulator::finishSync() {
1909 if (!mUsingSlotsProtocol) {
1910 clearSlots(-1);
1911 }
1912}
1913
1914bool MultiTouchMotionAccumulator::hasStylus() const {
1915 return mHaveStylus;
1916}
1917
Michael Wrightd02c5b62014-02-10 15:10:22 -08001918// --- MultiTouchMotionAccumulator::Slot ---
1919
1920MultiTouchMotionAccumulator::Slot::Slot() {
1921 clear();
1922}
1923
1924void MultiTouchMotionAccumulator::Slot::clear() {
1925 mInUse = false;
1926 mHaveAbsMTTouchMinor = false;
1927 mHaveAbsMTWidthMinor = false;
1928 mHaveAbsMTToolType = false;
1929 mAbsMTPositionX = 0;
1930 mAbsMTPositionY = 0;
1931 mAbsMTTouchMajor = 0;
1932 mAbsMTTouchMinor = 0;
1933 mAbsMTWidthMajor = 0;
1934 mAbsMTWidthMinor = 0;
1935 mAbsMTOrientation = 0;
1936 mAbsMTTrackingId = -1;
1937 mAbsMTPressure = 0;
1938 mAbsMTDistance = 0;
1939 mAbsMTToolType = 0;
1940}
1941
1942int32_t MultiTouchMotionAccumulator::Slot::getToolType() const {
1943 if (mHaveAbsMTToolType) {
1944 switch (mAbsMTToolType) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001945 case MT_TOOL_FINGER:
1946 return AMOTION_EVENT_TOOL_TYPE_FINGER;
1947 case MT_TOOL_PEN:
1948 return AMOTION_EVENT_TOOL_TYPE_STYLUS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08001949 }
1950 }
1951 return AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
1952}
1953
Michael Wrightd02c5b62014-02-10 15:10:22 -08001954// --- InputMapper ---
1955
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001956InputMapper::InputMapper(InputDevice* device) : mDevice(device), mContext(device->getContext()) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001957
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001958InputMapper::~InputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001959
1960void InputMapper::populateDeviceInfo(InputDeviceInfo* info) {
1961 info->addSource(getSources());
1962}
1963
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001964void InputMapper::dump(std::string& dump) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001965
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001966void InputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
1967 uint32_t changes) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001968
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001969void InputMapper::reset(nsecs_t when) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001970
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001971void InputMapper::timeoutExpired(nsecs_t when) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001972
1973int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
1974 return AKEY_STATE_UNKNOWN;
1975}
1976
1977int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
1978 return AKEY_STATE_UNKNOWN;
1979}
1980
1981int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
1982 return AKEY_STATE_UNKNOWN;
1983}
1984
1985bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001986 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08001987 return false;
1988}
1989
1990void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001991 int32_t token) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001992
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001993void InputMapper::cancelVibrate(int32_t token) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08001994
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07001995void InputMapper::cancelTouch(nsecs_t when) {}
Jeff Brownc9aa6282015-02-11 19:03:28 -08001996
Michael Wrightd02c5b62014-02-10 15:10:22 -08001997int32_t InputMapper::getMetaState() {
1998 return 0;
1999}
2000
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002001void InputMapper::updateMetaState(int32_t keyCode) {}
Andrii Kulian763a3a42016-03-08 10:46:16 -08002002
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002003void InputMapper::updateExternalStylusState(const StylusState& state) {}
Michael Wright842500e2015-03-13 17:32:02 -07002004
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002005void InputMapper::fadePointer() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002006
2007status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) {
2008 return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo);
2009}
2010
2011void InputMapper::bumpGeneration() {
2012 mDevice->bumpGeneration();
2013}
2014
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002015void InputMapper::dumpRawAbsoluteAxisInfo(std::string& dump, const RawAbsoluteAxisInfo& axis,
2016 const char* name) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002017 if (axis.valid) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002018 dump += StringPrintf(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n", name,
2019 axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002020 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002021 dump += StringPrintf(INDENT4 "%s: unknown range\n", name);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002022 }
2023}
2024
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002025void InputMapper::dumpStylusState(std::string& dump, const StylusState& state) {
2026 dump += StringPrintf(INDENT4 "When: %" PRId64 "\n", state.when);
2027 dump += StringPrintf(INDENT4 "Pressure: %f\n", state.pressure);
2028 dump += StringPrintf(INDENT4 "Button State: 0x%08x\n", state.buttons);
2029 dump += StringPrintf(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType);
Michael Wright842500e2015-03-13 17:32:02 -07002030}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002031
2032// --- SwitchInputMapper ---
2033
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002034SwitchInputMapper::SwitchInputMapper(InputDevice* device)
2035 : InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002036
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002037SwitchInputMapper::~SwitchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002038
2039uint32_t SwitchInputMapper::getSources() {
2040 return AINPUT_SOURCE_SWITCH;
2041}
2042
2043void SwitchInputMapper::process(const RawEvent* rawEvent) {
2044 switch (rawEvent->type) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002045 case EV_SW:
2046 processSwitch(rawEvent->code, rawEvent->value);
2047 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002048
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002049 case EV_SYN:
2050 if (rawEvent->code == SYN_REPORT) {
2051 sync(rawEvent->when);
2052 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002053 }
2054}
2055
2056void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) {
2057 if (switchCode >= 0 && switchCode < 32) {
2058 if (switchValue) {
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002059 mSwitchValues |= 1 << switchCode;
2060 } else {
2061 mSwitchValues &= ~(1 << switchCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002062 }
2063 mUpdatedSwitchMask |= 1 << switchCode;
2064 }
2065}
2066
2067void SwitchInputMapper::sync(nsecs_t when) {
2068 if (mUpdatedSwitchMask) {
Michael Wright3da3b842014-08-29 16:16:26 -07002069 uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002070 NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002071 mUpdatedSwitchMask);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002072 getListener()->notifySwitch(&args);
2073
Michael Wrightd02c5b62014-02-10 15:10:22 -08002074 mUpdatedSwitchMask = 0;
2075 }
2076}
2077
2078int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) {
2079 return getEventHub()->getSwitchState(getDeviceId(), switchCode);
2080}
2081
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002082void SwitchInputMapper::dump(std::string& dump) {
2083 dump += INDENT2 "Switch Input Mapper:\n";
2084 dump += StringPrintf(INDENT3 "SwitchValues: %x\n", mSwitchValues);
Michael Wrightbcbf97e2014-08-29 14:31:32 -07002085}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002086
2087// --- VibratorInputMapper ---
2088
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002089VibratorInputMapper::VibratorInputMapper(InputDevice* device)
2090 : InputMapper(device), mVibrating(false) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002091
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002092VibratorInputMapper::~VibratorInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002093
2094uint32_t VibratorInputMapper::getSources() {
2095 return 0;
2096}
2097
2098void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2099 InputMapper::populateDeviceInfo(info);
2100
2101 info->setVibrator(true);
2102}
2103
2104void VibratorInputMapper::process(const RawEvent* rawEvent) {
2105 // TODO: Handle FF_STATUS, although it does not seem to be widely supported.
2106}
2107
2108void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002109 int32_t token) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002110#if DEBUG_VIBRATOR
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002111 std::string patternStr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002112 for (size_t i = 0; i < patternSize; i++) {
2113 if (i != 0) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002114 patternStr += ", ";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002115 }
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002116 patternStr += StringPrintf("%" PRId64, pattern[i]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002117 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002118 ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%zd, token=%d", getDeviceId(),
2119 patternStr.c_str(), repeat, token);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002120#endif
2121
2122 mVibrating = true;
2123 memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t));
2124 mPatternSize = patternSize;
2125 mRepeat = repeat;
2126 mToken = token;
2127 mIndex = -1;
2128
2129 nextStep();
2130}
2131
2132void VibratorInputMapper::cancelVibrate(int32_t token) {
2133#if DEBUG_VIBRATOR
2134 ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token);
2135#endif
2136
2137 if (mVibrating && mToken == token) {
2138 stopVibrating();
2139 }
2140}
2141
2142void VibratorInputMapper::timeoutExpired(nsecs_t when) {
2143 if (mVibrating) {
2144 if (when >= mNextStepTime) {
2145 nextStep();
2146 } else {
2147 getContext()->requestTimeoutAtTime(mNextStepTime);
2148 }
2149 }
2150}
2151
2152void VibratorInputMapper::nextStep() {
2153 mIndex += 1;
2154 if (size_t(mIndex) >= mPatternSize) {
2155 if (mRepeat < 0) {
2156 // We are done.
2157 stopVibrating();
2158 return;
2159 }
2160 mIndex = mRepeat;
2161 }
2162
2163 bool vibratorOn = mIndex & 1;
2164 nsecs_t duration = mPattern[mIndex];
2165 if (vibratorOn) {
2166#if DEBUG_VIBRATOR
Siarhei Vishniakou5d83f602017-09-12 12:40:29 -07002167 ALOGD("nextStep: sending vibrate deviceId=%d, duration=%" PRId64, getDeviceId(), duration);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002168#endif
2169 getEventHub()->vibrate(getDeviceId(), duration);
2170 } else {
2171#if DEBUG_VIBRATOR
2172 ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId());
2173#endif
2174 getEventHub()->cancelVibrate(getDeviceId());
2175 }
2176 nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
2177 mNextStepTime = now + duration;
2178 getContext()->requestTimeoutAtTime(mNextStepTime);
2179#if DEBUG_VIBRATOR
2180 ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f);
2181#endif
2182}
2183
2184void VibratorInputMapper::stopVibrating() {
2185 mVibrating = false;
2186#if DEBUG_VIBRATOR
2187 ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId());
2188#endif
2189 getEventHub()->cancelVibrate(getDeviceId());
2190}
2191
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002192void VibratorInputMapper::dump(std::string& dump) {
2193 dump += INDENT2 "Vibrator Input Mapper:\n";
2194 dump += StringPrintf(INDENT3 "Vibrating: %s\n", toString(mVibrating));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002195}
2196
Michael Wrightd02c5b62014-02-10 15:10:22 -08002197// --- KeyboardInputMapper ---
2198
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002199KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType)
2200 : InputMapper(device), mSource(source), mKeyboardType(keyboardType) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002201
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002202KeyboardInputMapper::~KeyboardInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002203
2204uint32_t KeyboardInputMapper::getSources() {
2205 return mSource;
2206}
2207
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002208int32_t KeyboardInputMapper::getOrientation() {
2209 if (mViewport) {
2210 return mViewport->orientation;
2211 }
2212 return DISPLAY_ORIENTATION_0;
2213}
2214
2215int32_t KeyboardInputMapper::getDisplayId() {
2216 if (mViewport) {
2217 return mViewport->displayId;
2218 }
2219 return ADISPLAY_ID_NONE;
2220}
2221
Michael Wrightd02c5b62014-02-10 15:10:22 -08002222void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2223 InputMapper::populateDeviceInfo(info);
2224
2225 info->setKeyboardType(mKeyboardType);
2226 info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId()));
2227}
2228
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002229void KeyboardInputMapper::dump(std::string& dump) {
2230 dump += INDENT2 "Keyboard Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002231 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002232 dump += StringPrintf(INDENT3 "KeyboardType: %d\n", mKeyboardType);
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002233 dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002234 dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
2235 dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
2236 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002237}
2238
Arthur Hung2c9a3342019-07-23 14:18:59 +08002239std::optional<DisplayViewport> KeyboardInputMapper::findViewport(
2240 nsecs_t when, const InputReaderConfiguration* config) {
2241 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
2242 if (displayPort) {
2243 // Find the viewport that contains the same port
2244 return mDevice->getAssociatedViewport();
2245 }
2246
2247 // No associated display defined, try to find default display if orientationAware.
2248 if (mParameters.orientationAware) {
2249 return config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
2250 }
2251
2252 return std::nullopt;
2253}
2254
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002255void KeyboardInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
2256 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002257 InputMapper::configure(when, config, changes);
2258
2259 if (!changes) { // first time only
2260 // Configure basic parameters.
2261 configureParameters();
2262 }
2263
2264 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Arthur Hung2c9a3342019-07-23 14:18:59 +08002265 mViewport = findViewport(when, config);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002266 }
2267}
2268
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002269static void mapStemKey(int32_t keyCode, const PropertyMap& config, char const* property) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002270 int32_t mapped = 0;
2271 if (config.tryGetProperty(String8(property), mapped) && mapped > 0) {
2272 for (size_t i = 0; i < stemKeyRotationMapSize; i++) {
2273 if (stemKeyRotationMap[i][0] == keyCode) {
2274 stemKeyRotationMap[i][1] = mapped;
2275 return;
2276 }
2277 }
2278 }
2279}
2280
Michael Wrightd02c5b62014-02-10 15:10:22 -08002281void KeyboardInputMapper::configureParameters() {
2282 mParameters.orientationAware = false;
Ivan Podogovb9afef32017-02-13 15:34:32 +00002283 const PropertyMap& config = getDevice()->getConfiguration();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002284 config.tryGetProperty(String8("keyboard.orientationAware"), mParameters.orientationAware);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002285
Michael Wrightd02c5b62014-02-10 15:10:22 -08002286 if (mParameters.orientationAware) {
Ivan Podogovb9afef32017-02-13 15:34:32 +00002287 mapStemKey(AKEYCODE_STEM_PRIMARY, config, "keyboard.rotated.stem_primary");
2288 mapStemKey(AKEYCODE_STEM_1, config, "keyboard.rotated.stem_1");
2289 mapStemKey(AKEYCODE_STEM_2, config, "keyboard.rotated.stem_2");
2290 mapStemKey(AKEYCODE_STEM_3, config, "keyboard.rotated.stem_3");
Michael Wrightd02c5b62014-02-10 15:10:22 -08002291 }
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002292
2293 mParameters.handlesKeyRepeat = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002294 config.tryGetProperty(String8("keyboard.handlesKeyRepeat"), mParameters.handlesKeyRepeat);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002295}
2296
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002297void KeyboardInputMapper::dumpParameters(std::string& dump) {
2298 dump += INDENT3 "Parameters:\n";
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002299 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
2300 dump += StringPrintf(INDENT4 "HandlesKeyRepeat: %s\n", toString(mParameters.handlesKeyRepeat));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002301}
2302
2303void KeyboardInputMapper::reset(nsecs_t when) {
2304 mMetaState = AMETA_NONE;
2305 mDownTime = 0;
2306 mKeyDowns.clear();
2307 mCurrentHidUsage = 0;
2308
2309 resetLedState();
2310
2311 InputMapper::reset(when);
2312}
2313
2314void KeyboardInputMapper::process(const RawEvent* rawEvent) {
2315 switch (rawEvent->type) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002316 case EV_KEY: {
2317 int32_t scanCode = rawEvent->code;
2318 int32_t usageCode = mCurrentHidUsage;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002319 mCurrentHidUsage = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002320
2321 if (isKeyboardOrGamepadKey(scanCode)) {
2322 processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode);
2323 }
2324 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002325 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002326 case EV_MSC: {
2327 if (rawEvent->code == MSC_SCAN) {
2328 mCurrentHidUsage = rawEvent->value;
2329 }
2330 break;
2331 }
2332 case EV_SYN: {
2333 if (rawEvent->code == SYN_REPORT) {
2334 mCurrentHidUsage = 0;
2335 }
2336 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002337 }
2338}
2339
2340bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002341 return scanCode < BTN_MOUSE || scanCode >= KEY_OK ||
2342 (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) ||
2343 (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002344}
2345
Michael Wright58ba9882017-07-26 16:19:11 +01002346bool KeyboardInputMapper::isMediaKey(int32_t keyCode) {
2347 switch (keyCode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002348 case AKEYCODE_MEDIA_PLAY:
2349 case AKEYCODE_MEDIA_PAUSE:
2350 case AKEYCODE_MEDIA_PLAY_PAUSE:
2351 case AKEYCODE_MUTE:
2352 case AKEYCODE_HEADSETHOOK:
2353 case AKEYCODE_MEDIA_STOP:
2354 case AKEYCODE_MEDIA_NEXT:
2355 case AKEYCODE_MEDIA_PREVIOUS:
2356 case AKEYCODE_MEDIA_REWIND:
2357 case AKEYCODE_MEDIA_RECORD:
2358 case AKEYCODE_MEDIA_FAST_FORWARD:
2359 case AKEYCODE_MEDIA_SKIP_FORWARD:
2360 case AKEYCODE_MEDIA_SKIP_BACKWARD:
2361 case AKEYCODE_MEDIA_STEP_FORWARD:
2362 case AKEYCODE_MEDIA_STEP_BACKWARD:
2363 case AKEYCODE_MEDIA_AUDIO_TRACK:
2364 case AKEYCODE_VOLUME_UP:
2365 case AKEYCODE_VOLUME_DOWN:
2366 case AKEYCODE_VOLUME_MUTE:
2367 case AKEYCODE_TV_AUDIO_DESCRIPTION:
2368 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_UP:
2369 case AKEYCODE_TV_AUDIO_DESCRIPTION_MIX_DOWN:
2370 return true;
Michael Wright58ba9882017-07-26 16:19:11 +01002371 }
2372 return false;
2373}
2374
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002375void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, int32_t usageCode) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002376 int32_t keyCode;
2377 int32_t keyMetaState;
2378 uint32_t policyFlags;
2379
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002380 if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState, &keyCode,
2381 &keyMetaState, &policyFlags)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002382 keyCode = AKEYCODE_UNKNOWN;
2383 keyMetaState = mMetaState;
2384 policyFlags = 0;
2385 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002386
2387 if (down) {
2388 // Rotate key codes according to orientation if needed.
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +01002389 if (mParameters.orientationAware) {
2390 keyCode = rotateKeyCode(keyCode, getOrientation());
Michael Wrightd02c5b62014-02-10 15:10:22 -08002391 }
2392
2393 // Add key down.
2394 ssize_t keyDownIndex = findKeyDown(scanCode);
2395 if (keyDownIndex >= 0) {
2396 // key repeat, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002397 keyCode = mKeyDowns[keyDownIndex].keyCode;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002398 } else {
2399 // key down
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002400 if ((policyFlags & POLICY_FLAG_VIRTUAL) &&
2401 mContext->shouldDropVirtualKey(when, getDevice(), keyCode, scanCode)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002402 return;
2403 }
Jeff Brownc9aa6282015-02-11 19:03:28 -08002404 if (policyFlags & POLICY_FLAG_GESTURE) {
2405 mDevice->cancelTouch(when);
2406 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002407
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002408 KeyDown keyDown;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002409 keyDown.keyCode = keyCode;
2410 keyDown.scanCode = scanCode;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002411 mKeyDowns.push_back(keyDown);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002412 }
2413
2414 mDownTime = when;
2415 } else {
2416 // Remove key down.
2417 ssize_t keyDownIndex = findKeyDown(scanCode);
2418 if (keyDownIndex >= 0) {
2419 // key up, be sure to use same keycode as before in case of rotation
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002420 keyCode = mKeyDowns[keyDownIndex].keyCode;
2421 mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002422 } else {
2423 // key was not actually down
2424 ALOGI("Dropping key up from device %s because the key was not down. "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002425 "keyCode=%d, scanCode=%d",
2426 getDeviceName().c_str(), keyCode, scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002427 return;
2428 }
2429 }
2430
Andrii Kulian763a3a42016-03-08 10:46:16 -08002431 if (updateMetaStateIfNeeded(keyCode, down)) {
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07002432 // If global meta state changed send it along with the key.
2433 // If it has not changed then we'll use what keymap gave us,
2434 // since key replacement logic might temporarily reset a few
2435 // meta bits for given key.
Andrii Kulian763a3a42016-03-08 10:46:16 -08002436 keyMetaState = mMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002437 }
2438
2439 nsecs_t downTime = mDownTime;
2440
2441 // Key down on external an keyboard should wake the device.
2442 // We don't do this for internal keyboards to prevent them from waking up in your pocket.
2443 // For internal keyboards, the key layout file should specify the policy flags for
2444 // each wake key individually.
2445 // TODO: Use the input device configuration to control this behavior more finely.
Michael Wright58ba9882017-07-26 16:19:11 +01002446 if (down && getDevice()->isExternal() && !isMediaKey(keyCode)) {
Michael Wright872db4f2014-04-22 15:03:51 -07002447 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002448 }
2449
Michael Wrightdcfcf5d2014-03-17 12:58:21 -07002450 if (mParameters.handlesKeyRepeat) {
2451 policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
2452 }
2453
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002454 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource, getDisplayId(),
2455 policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
2456 AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002457 getListener()->notifyKey(&args);
2458}
2459
2460ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) {
2461 size_t n = mKeyDowns.size();
2462 for (size_t i = 0; i < n; i++) {
2463 if (mKeyDowns[i].scanCode == scanCode) {
2464 return i;
2465 }
2466 }
2467 return -1;
2468}
2469
2470int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
2471 return getEventHub()->getKeyCodeState(getDeviceId(), keyCode);
2472}
2473
2474int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2475 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2476}
2477
2478bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002479 const int32_t* keyCodes, uint8_t* outFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002480 return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags);
2481}
2482
2483int32_t KeyboardInputMapper::getMetaState() {
2484 return mMetaState;
2485}
2486
Andrii Kulian763a3a42016-03-08 10:46:16 -08002487void KeyboardInputMapper::updateMetaState(int32_t keyCode) {
2488 updateMetaStateIfNeeded(keyCode, false);
2489}
2490
2491bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) {
2492 int32_t oldMetaState = mMetaState;
2493 int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState);
2494 bool metaStateChanged = oldMetaState != newMetaState;
2495 if (metaStateChanged) {
2496 mMetaState = newMetaState;
2497 updateLedState(false);
2498
2499 getContext()->updateGlobalMetaState();
2500 }
2501
2502 return metaStateChanged;
2503}
2504
Michael Wrightd02c5b62014-02-10 15:10:22 -08002505void KeyboardInputMapper::resetLedState() {
2506 initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK);
2507 initializeLedState(mNumLockLedState, ALED_NUM_LOCK);
2508 initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK);
2509
2510 updateLedState(true);
2511}
2512
2513void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) {
2514 ledState.avail = getEventHub()->hasLed(getDeviceId(), led);
2515 ledState.on = false;
2516}
2517
2518void KeyboardInputMapper::updateLedState(bool reset) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002519 updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK, AMETA_CAPS_LOCK_ON, reset);
2520 updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK, AMETA_NUM_LOCK_ON, reset);
2521 updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK, AMETA_SCROLL_LOCK_ON, reset);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002522}
2523
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002524void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState, int32_t led,
2525 int32_t modifier, bool reset) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002526 if (ledState.avail) {
2527 bool desiredState = (mMetaState & modifier) != 0;
2528 if (reset || ledState.on != desiredState) {
2529 getEventHub()->setLedState(getDeviceId(), led, desiredState);
2530 ledState.on = desiredState;
2531 }
2532 }
2533}
2534
Arthur Hung2c9a3342019-07-23 14:18:59 +08002535std::optional<int32_t> KeyboardInputMapper::getAssociatedDisplayId() {
2536 if (mViewport) {
2537 return std::make_optional(mViewport->displayId);
2538 }
2539 return std::nullopt;
2540}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002541
2542// --- CursorInputMapper ---
2543
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002544CursorInputMapper::CursorInputMapper(InputDevice* device) : InputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002545
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002546CursorInputMapper::~CursorInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08002547
2548uint32_t CursorInputMapper::getSources() {
2549 return mSource;
2550}
2551
2552void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2553 InputMapper::populateDeviceInfo(info);
2554
2555 if (mParameters.mode == Parameters::MODE_POINTER) {
2556 float minX, minY, maxX, maxY;
2557 if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) {
2558 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f);
2559 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f);
2560 }
2561 } else {
2562 info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f);
2563 info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f);
2564 }
2565 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2566
2567 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
2568 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2569 }
2570 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
2571 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
2572 }
2573}
2574
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002575void CursorInputMapper::dump(std::string& dump) {
2576 dump += INDENT2 "Cursor Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08002577 dumpParameters(dump);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002578 dump += StringPrintf(INDENT3 "XScale: %0.3f\n", mXScale);
2579 dump += StringPrintf(INDENT3 "YScale: %0.3f\n", mYScale);
2580 dump += StringPrintf(INDENT3 "XPrecision: %0.3f\n", mXPrecision);
2581 dump += StringPrintf(INDENT3 "YPrecision: %0.3f\n", mYPrecision);
2582 dump += StringPrintf(INDENT3 "HaveVWheel: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002583 toString(mCursorScrollAccumulator.haveRelativeVWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002584 dump += StringPrintf(INDENT3 "HaveHWheel: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002585 toString(mCursorScrollAccumulator.haveRelativeHWheel()));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002586 dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
2587 dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
2588 dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
2589 dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
2590 dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
2591 dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002592}
2593
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002594void CursorInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
2595 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002596 InputMapper::configure(when, config, changes);
2597
2598 if (!changes) { // first time only
2599 mCursorScrollAccumulator.configure(getDevice());
2600
2601 // Configure basic parameters.
2602 configureParameters();
2603
2604 // Configure device mode.
2605 switch (mParameters.mode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002606 case Parameters::MODE_POINTER_RELATIVE:
2607 // Should not happen during first time configuration.
2608 ALOGE("Cannot start a device in MODE_POINTER_RELATIVE, starting in MODE_POINTER");
2609 mParameters.mode = Parameters::MODE_POINTER;
2610 [[fallthrough]];
2611 case Parameters::MODE_POINTER:
2612 mSource = AINPUT_SOURCE_MOUSE;
2613 mXPrecision = 1.0f;
2614 mYPrecision = 1.0f;
2615 mXScale = 1.0f;
2616 mYScale = 1.0f;
2617 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
2618 break;
2619 case Parameters::MODE_NAVIGATION:
2620 mSource = AINPUT_SOURCE_TRACKBALL;
2621 mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2622 mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD;
2623 mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2624 mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD;
2625 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002626 }
2627
2628 mVWheelScale = 1.0f;
2629 mHWheelScale = 1.0f;
2630 }
2631
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002632 if ((!changes && config->pointerCapture) ||
2633 (changes & InputReaderConfiguration::CHANGE_POINTER_CAPTURE)) {
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002634 if (config->pointerCapture) {
2635 if (mParameters.mode == Parameters::MODE_POINTER) {
2636 mParameters.mode = Parameters::MODE_POINTER_RELATIVE;
2637 mSource = AINPUT_SOURCE_MOUSE_RELATIVE;
2638 // Keep PointerController around in order to preserve the pointer position.
2639 mPointerController->fade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2640 } else {
2641 ALOGE("Cannot request pointer capture, device is not in MODE_POINTER");
2642 }
2643 } else {
2644 if (mParameters.mode == Parameters::MODE_POINTER_RELATIVE) {
2645 mParameters.mode = Parameters::MODE_POINTER;
2646 mSource = AINPUT_SOURCE_MOUSE;
2647 } else {
2648 ALOGE("Cannot release pointer capture, device is not in MODE_POINTER_RELATIVE");
2649 }
2650 }
2651 bumpGeneration();
2652 if (changes) {
2653 getDevice()->notifyReset(when);
2654 }
2655 }
2656
Michael Wrightd02c5b62014-02-10 15:10:22 -08002657 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
2658 mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters);
2659 mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters);
2660 mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters);
2661 }
2662
2663 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08002664 mOrientation = DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002665 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002666 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07002667 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07002668 if (internalViewport) {
2669 mOrientation = internalViewport->orientation;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002670 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002671 }
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002672
2673 // Update the PointerController if viewports changed.
Arthur Hungc23540e2018-11-29 20:42:11 +08002674 if (mParameters.mode == Parameters::MODE_POINTER) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002675 getPolicy()->obtainPointerController(getDeviceId());
2676 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08002677 bumpGeneration();
2678 }
2679}
2680
2681void CursorInputMapper::configureParameters() {
2682 mParameters.mode = Parameters::MODE_POINTER;
2683 String8 cursorModeString;
2684 if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) {
2685 if (cursorModeString == "navigation") {
2686 mParameters.mode = Parameters::MODE_NAVIGATION;
2687 } else if (cursorModeString != "pointer" && cursorModeString != "default") {
2688 ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string());
2689 }
2690 }
2691
2692 mParameters.orientationAware = false;
2693 getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002694 mParameters.orientationAware);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002695
2696 mParameters.hasAssociatedDisplay = false;
2697 if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) {
2698 mParameters.hasAssociatedDisplay = true;
2699 }
2700}
2701
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002702void CursorInputMapper::dumpParameters(std::string& dump) {
2703 dump += INDENT3 "Parameters:\n";
2704 dump += StringPrintf(INDENT4 "HasAssociatedDisplay: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002705 toString(mParameters.hasAssociatedDisplay));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002706
2707 switch (mParameters.mode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002708 case Parameters::MODE_POINTER:
2709 dump += INDENT4 "Mode: pointer\n";
2710 break;
2711 case Parameters::MODE_POINTER_RELATIVE:
2712 dump += INDENT4 "Mode: relative pointer\n";
2713 break;
2714 case Parameters::MODE_NAVIGATION:
2715 dump += INDENT4 "Mode: navigation\n";
2716 break;
2717 default:
2718 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002719 }
2720
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002721 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Michael Wrightd02c5b62014-02-10 15:10:22 -08002722}
2723
2724void CursorInputMapper::reset(nsecs_t when) {
2725 mButtonState = 0;
2726 mDownTime = 0;
2727
2728 mPointerVelocityControl.reset();
2729 mWheelXVelocityControl.reset();
2730 mWheelYVelocityControl.reset();
2731
2732 mCursorButtonAccumulator.reset(getDevice());
2733 mCursorMotionAccumulator.reset(getDevice());
2734 mCursorScrollAccumulator.reset(getDevice());
2735
2736 InputMapper::reset(when);
2737}
2738
2739void CursorInputMapper::process(const RawEvent* rawEvent) {
2740 mCursorButtonAccumulator.process(rawEvent);
2741 mCursorMotionAccumulator.process(rawEvent);
2742 mCursorScrollAccumulator.process(rawEvent);
2743
2744 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
2745 sync(rawEvent->when);
2746 }
2747}
2748
2749void CursorInputMapper::sync(nsecs_t when) {
2750 int32_t lastButtonState = mButtonState;
2751 int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
2752 mButtonState = currentButtonState;
2753
2754 bool wasDown = isPointerDown(lastButtonState);
2755 bool down = isPointerDown(currentButtonState);
2756 bool downChanged;
2757 if (!wasDown && down) {
2758 mDownTime = when;
2759 downChanged = true;
2760 } else if (wasDown && !down) {
2761 downChanged = true;
2762 } else {
2763 downChanged = false;
2764 }
2765 nsecs_t downTime = mDownTime;
2766 bool buttonsChanged = currentButtonState != lastButtonState;
Michael Wright7b159c92015-05-14 14:48:03 +01002767 int32_t buttonsPressed = currentButtonState & ~lastButtonState;
2768 int32_t buttonsReleased = lastButtonState & ~currentButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002769
2770 float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale;
2771 float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale;
2772 bool moved = deltaX != 0 || deltaY != 0;
2773
2774 // Rotate delta according to orientation if needed.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002775 if (mParameters.orientationAware && mParameters.hasAssociatedDisplay &&
2776 (deltaX != 0.0f || deltaY != 0.0f)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002777 rotateDelta(mOrientation, &deltaX, &deltaY);
2778 }
2779
2780 // Move the pointer.
2781 PointerProperties pointerProperties;
2782 pointerProperties.clear();
2783 pointerProperties.id = 0;
2784 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE;
2785
2786 PointerCoords pointerCoords;
2787 pointerCoords.clear();
2788
2789 float vscroll = mCursorScrollAccumulator.getRelativeVWheel();
2790 float hscroll = mCursorScrollAccumulator.getRelativeHWheel();
2791 bool scrolled = vscroll != 0 || hscroll != 0;
2792
Yi Kong9b14ac62018-07-17 13:48:38 -07002793 mWheelYVelocityControl.move(when, nullptr, &vscroll);
2794 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002795
2796 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2797
2798 int32_t displayId;
Garfield Tan00f511d2019-06-12 16:55:40 -07002799 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
2800 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002801 if (mSource == AINPUT_SOURCE_MOUSE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002802 if (moved || scrolled || buttonsChanged) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002803 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002804
2805 if (moved) {
2806 mPointerController->move(deltaX, deltaY);
2807 }
2808
2809 if (buttonsChanged) {
2810 mPointerController->setButtonState(currentButtonState);
2811 }
2812
2813 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
2814 }
2815
Garfield Tan00f511d2019-06-12 16:55:40 -07002816 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
2817 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
2818 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
Jun Mukaifa1706a2015-12-03 01:14:46 -08002819 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
2820 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
Arthur Hungc7ad2d02018-12-18 17:41:29 +08002821 displayId = mPointerController->getDisplayId();
Michael Wrightd02c5b62014-02-10 15:10:22 -08002822 } else {
2823 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
2824 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY);
2825 displayId = ADISPLAY_ID_NONE;
2826 }
2827
2828 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
2829
2830 // Moving an external trackball or mouse should wake the device.
2831 // We don't do this for internal cursor devices to prevent them from waking up
2832 // the device in your pocket.
2833 // TODO: Use the input device configuration to control this behavior more finely.
2834 uint32_t policyFlags = 0;
2835 if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) {
Michael Wright872db4f2014-04-22 15:03:51 -07002836 policyFlags |= POLICY_FLAG_WAKE;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002837 }
2838
2839 // Synthesize key down from buttons if needed.
2840 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002841 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002842
2843 // Send motion event.
2844 if (downChanged || moved || scrolled || buttonsChanged) {
2845 int32_t metaState = mContext->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01002846 int32_t buttonState = lastButtonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08002847 int32_t motionEventAction;
2848 if (downChanged) {
2849 motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP;
Vladislav Kaznacheev78f97b32016-12-15 18:14:58 -08002850 } else if (down || (mSource != AINPUT_SOURCE_MOUSE)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002851 motionEventAction = AMOTION_EVENT_ACTION_MOVE;
2852 } else {
2853 motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE;
2854 }
2855
Michael Wright7b159c92015-05-14 14:48:03 +01002856 if (buttonsReleased) {
2857 BitSet32 released(buttonsReleased);
2858 while (!released.isEmpty()) {
2859 int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
2860 buttonState &= ~actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002861 NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002862 mSource, displayId, policyFlags,
2863 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2864 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002865 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002866 &pointerCoords, mXPrecision, mYPrecision,
2867 xCursorPosition, yCursorPosition, downTime,
2868 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002869 getListener()->notifyMotion(&releaseArgs);
2870 }
2871 }
2872
Prabir Pradhan42611e02018-11-27 14:04:02 -08002873 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
Garfield Tan00f511d2019-06-12 16:55:40 -07002874 displayId, policyFlags, motionEventAction, 0, 0, metaState,
2875 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002876 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
Garfield Tan00f511d2019-06-12 16:55:40 -07002877 mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
2878 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002879 getListener()->notifyMotion(&args);
2880
Michael Wright7b159c92015-05-14 14:48:03 +01002881 if (buttonsPressed) {
2882 BitSet32 pressed(buttonsPressed);
2883 while (!pressed.isEmpty()) {
2884 int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
2885 buttonState |= actionButton;
Prabir Pradhan42611e02018-11-27 14:04:02 -08002886 NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002887 mSource, displayId, policyFlags,
2888 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
2889 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002890 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002891 &pointerCoords, mXPrecision, mYPrecision,
2892 xCursorPosition, yCursorPosition, downTime,
2893 /* videoFrames */ {});
Michael Wright7b159c92015-05-14 14:48:03 +01002894 getListener()->notifyMotion(&pressArgs);
2895 }
2896 }
2897
2898 ALOG_ASSERT(buttonState == currentButtonState);
2899
Michael Wrightd02c5b62014-02-10 15:10:22 -08002900 // Send hover move after UP to tell the application that the mouse is hovering now.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002901 if (motionEventAction == AMOTION_EVENT_ACTION_UP && (mSource == AINPUT_SOURCE_MOUSE)) {
Garfield Tan00f511d2019-06-12 16:55:40 -07002902 NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
2903 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2904 0, metaState, currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002905 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002906 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002907 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002908 getListener()->notifyMotion(&hoverArgs);
2909 }
2910
2911 // Send scroll events.
2912 if (scrolled) {
2913 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
2914 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
2915
Prabir Pradhan42611e02018-11-27 14:04:02 -08002916 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07002917 mSource, displayId, policyFlags,
2918 AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
2919 currentButtonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002920 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
Garfield Tan00f511d2019-06-12 16:55:40 -07002921 &pointerCoords, mXPrecision, mYPrecision, xCursorPosition,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07002922 yCursorPosition, downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08002923 getListener()->notifyMotion(&scrollArgs);
2924 }
2925 }
2926
2927 // Synthesize key up from buttons if needed.
2928 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002929 displayId, policyFlags, lastButtonState, currentButtonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08002930
2931 mCursorMotionAccumulator.finishSync();
2932 mCursorScrollAccumulator.finishSync();
2933}
2934
2935int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
2936 if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) {
2937 return getEventHub()->getScanCodeState(getDeviceId(), scanCode);
2938 } else {
2939 return AKEY_STATE_UNKNOWN;
2940 }
2941}
2942
2943void CursorInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07002944 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08002945 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
2946 }
2947}
2948
Arthur Hung2c9a3342019-07-23 14:18:59 +08002949std::optional<int32_t> CursorInputMapper::getAssociatedDisplayId() {
Arthur Hungc23540e2018-11-29 20:42:11 +08002950 if (mParameters.hasAssociatedDisplay) {
2951 if (mParameters.mode == Parameters::MODE_POINTER) {
2952 return std::make_optional(mPointerController->getDisplayId());
2953 } else {
2954 // If the device is orientationAware and not a mouse,
2955 // it expects to dispatch events to any display
2956 return std::make_optional(ADISPLAY_ID_NONE);
2957 }
2958 }
2959 return std::nullopt;
2960}
2961
Prashant Malani1941ff52015-08-11 18:29:28 -07002962// --- RotaryEncoderInputMapper ---
2963
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002964RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device)
2965 : InputMapper(device), mOrientation(DISPLAY_ORIENTATION_0) {
Prashant Malani1941ff52015-08-11 18:29:28 -07002966 mSource = AINPUT_SOURCE_ROTARY_ENCODER;
2967}
2968
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002969RotaryEncoderInputMapper::~RotaryEncoderInputMapper() {}
Prashant Malani1941ff52015-08-11 18:29:28 -07002970
2971uint32_t RotaryEncoderInputMapper::getSources() {
2972 return mSource;
2973}
2974
2975void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
2976 InputMapper::populateDeviceInfo(info);
2977
2978 if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002979 float res = 0.0f;
2980 if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) {
2981 ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n");
2982 }
2983 if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002984 mScalingFactor)) {
Prashant Malanidae627a2016-01-11 17:08:18 -08002985 ALOGW("Rotary Encoder device configuration file didn't specify scaling factor,"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002986 "default to 1.0!\n");
Prashant Malanidae627a2016-01-11 17:08:18 -08002987 mScalingFactor = 1.0f;
2988 }
2989 info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002990 res * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07002991 }
2992}
2993
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08002994void RotaryEncoderInputMapper::dump(std::string& dump) {
2995 dump += INDENT2 "Rotary Encoder Input Mapper:\n";
2996 dump += StringPrintf(INDENT3 "HaveWheel: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07002997 toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel()));
Prashant Malani1941ff52015-08-11 18:29:28 -07002998}
2999
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003000void RotaryEncoderInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
3001 uint32_t changes) {
Prashant Malani1941ff52015-08-11 18:29:28 -07003002 InputMapper::configure(when, config, changes);
3003 if (!changes) {
3004 mRotaryEncoderScrollAccumulator.configure(getDevice());
3005 }
Siarhei Vishniakoud00e7872018-08-09 09:22:45 -07003006 if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003007 std::optional<DisplayViewport> internalViewport =
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003008 config->getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
Siarhei Vishniakou05a8fe22018-10-03 16:38:28 -07003009 if (internalViewport) {
3010 mOrientation = internalViewport->orientation;
Ivan Podogovad437252016-09-29 16:29:55 +01003011 } else {
3012 mOrientation = DISPLAY_ORIENTATION_0;
3013 }
3014 }
Prashant Malani1941ff52015-08-11 18:29:28 -07003015}
3016
3017void RotaryEncoderInputMapper::reset(nsecs_t when) {
3018 mRotaryEncoderScrollAccumulator.reset(getDevice());
3019
3020 InputMapper::reset(when);
3021}
3022
3023void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) {
3024 mRotaryEncoderScrollAccumulator.process(rawEvent);
3025
3026 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
3027 sync(rawEvent->when);
3028 }
3029}
3030
3031void RotaryEncoderInputMapper::sync(nsecs_t when) {
3032 PointerCoords pointerCoords;
3033 pointerCoords.clear();
3034
3035 PointerProperties pointerProperties;
3036 pointerProperties.clear();
3037 pointerProperties.id = 0;
3038 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
3039
3040 float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel();
3041 bool scrolled = scroll != 0;
3042
3043 // This is not a pointer, so it's not associated with a display.
3044 int32_t displayId = ADISPLAY_ID_NONE;
3045
3046 // Moving the rotary encoder should wake the device (if specified).
3047 uint32_t policyFlags = 0;
3048 if (scrolled && getDevice()->isExternal()) {
3049 policyFlags |= POLICY_FLAG_WAKE;
3050 }
3051
Ivan Podogovad437252016-09-29 16:29:55 +01003052 if (mOrientation == DISPLAY_ORIENTATION_180) {
3053 scroll = -scroll;
3054 }
3055
Prashant Malani1941ff52015-08-11 18:29:28 -07003056 // Send motion event.
3057 if (scrolled) {
3058 int32_t metaState = mContext->getGlobalMetaState();
Prashant Malanidae627a2016-01-11 17:08:18 -08003059 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
Prashant Malani1941ff52015-08-11 18:29:28 -07003060
Garfield Tan00f511d2019-06-12 16:55:40 -07003061 NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
3062 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0,
3063 metaState, /* buttonState */ 0, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07003064 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
3065 &pointerCoords, 0, 0, AMOTION_EVENT_INVALID_CURSOR_POSITION,
Garfield Tan00f511d2019-06-12 16:55:40 -07003066 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Prashant Malani1941ff52015-08-11 18:29:28 -07003067 getListener()->notifyMotion(&scrollArgs);
3068 }
3069
3070 mRotaryEncoderScrollAccumulator.finishSync();
3071}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003072
3073// --- TouchInputMapper ---
3074
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003075TouchInputMapper::TouchInputMapper(InputDevice* device)
3076 : InputMapper(device),
3077 mSource(0),
3078 mDeviceMode(DEVICE_MODE_DISABLED),
3079 mSurfaceWidth(-1),
3080 mSurfaceHeight(-1),
3081 mSurfaceLeft(0),
3082 mSurfaceTop(0),
3083 mPhysicalWidth(-1),
3084 mPhysicalHeight(-1),
3085 mPhysicalLeft(0),
3086 mPhysicalTop(0),
3087 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003088
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003089TouchInputMapper::~TouchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08003090
3091uint32_t TouchInputMapper::getSources() {
3092 return mSource;
3093}
3094
3095void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
3096 InputMapper::populateDeviceInfo(info);
3097
3098 if (mDeviceMode != DEVICE_MODE_DISABLED) {
3099 info->addMotionRange(mOrientedRanges.x);
3100 info->addMotionRange(mOrientedRanges.y);
3101 info->addMotionRange(mOrientedRanges.pressure);
3102
3103 if (mOrientedRanges.haveSize) {
3104 info->addMotionRange(mOrientedRanges.size);
3105 }
3106
3107 if (mOrientedRanges.haveTouchSize) {
3108 info->addMotionRange(mOrientedRanges.touchMajor);
3109 info->addMotionRange(mOrientedRanges.touchMinor);
3110 }
3111
3112 if (mOrientedRanges.haveToolSize) {
3113 info->addMotionRange(mOrientedRanges.toolMajor);
3114 info->addMotionRange(mOrientedRanges.toolMinor);
3115 }
3116
3117 if (mOrientedRanges.haveOrientation) {
3118 info->addMotionRange(mOrientedRanges.orientation);
3119 }
3120
3121 if (mOrientedRanges.haveDistance) {
3122 info->addMotionRange(mOrientedRanges.distance);
3123 }
3124
3125 if (mOrientedRanges.haveTilt) {
3126 info->addMotionRange(mOrientedRanges.tilt);
3127 }
3128
3129 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
3130 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003131 0.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003132 }
3133 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
3134 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003135 0.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003136 }
3137 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
3138 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
3139 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
3140 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003141 x.fuzz, x.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003142 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003143 y.fuzz, y.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003144 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003145 x.fuzz, x.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003146 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003147 y.fuzz, y.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003148 }
3149 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
3150 }
3151}
3152
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003153void TouchInputMapper::dump(std::string& dump) {
3154 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003155 dumpParameters(dump);
3156 dumpVirtualKeys(dump);
3157 dumpRawPointerAxes(dump);
3158 dumpCalibration(dump);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07003159 dumpAffineTransformation(dump);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003160 dumpSurface(dump);
3161
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003162 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
3163 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
3164 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
3165 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
3166 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
3167 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
3168 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
3169 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
3170 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
3171 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
3172 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
3173 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
3174 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
3175 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
3176 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
3177 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
3178 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003179
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003180 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
3181 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003182 mLastRawState.rawPointerData.pointerCount);
Michael Wright842500e2015-03-13 17:32:02 -07003183 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
3184 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003185 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003186 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
3187 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
3188 "toolType=%d, isHovering=%s\n",
3189 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
3190 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
3191 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
3192 pointer.distance, pointer.toolType, toString(pointer.isHovering));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003193 }
3194
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003195 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
3196 mLastCookedState.buttonState);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003197 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003198 mLastCookedState.cookedPointerData.pointerCount);
Michael Wright842500e2015-03-13 17:32:02 -07003199 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
3200 const PointerProperties& pointerProperties =
3201 mLastCookedState.cookedPointerData.pointerProperties[i];
3202 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003203 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003204 "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, "
3205 "toolMinor=%0.3f, "
3206 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
3207 "toolType=%d, isHovering=%s\n",
3208 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
3209 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
3210 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
3211 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
3212 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
3213 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
3214 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
3215 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
3216 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
3217 pointerProperties.toolType,
3218 toString(mLastCookedState.cookedPointerData.isHovering(i)));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003219 }
3220
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003221 dump += INDENT3 "Stylus Fusion:\n";
3222 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003223 toString(mExternalStylusConnected));
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003224 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
3225 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003226 mExternalStylusFusionTimeout);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003227 dump += INDENT3 "External Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07003228 dumpStylusState(dump, mExternalStylusState);
3229
Michael Wrightd02c5b62014-02-10 15:10:22 -08003230 if (mDeviceMode == DEVICE_MODE_POINTER) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003231 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003232 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
3233 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
3234 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
3235 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
3236 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003237 }
3238}
3239
Santos Cordonfa5cf462017-04-05 10:37:00 -07003240const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
3241 switch (deviceMode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003242 case DEVICE_MODE_DISABLED:
3243 return "disabled";
3244 case DEVICE_MODE_DIRECT:
3245 return "direct";
3246 case DEVICE_MODE_UNSCALED:
3247 return "unscaled";
3248 case DEVICE_MODE_NAVIGATION:
3249 return "navigation";
3250 case DEVICE_MODE_POINTER:
3251 return "pointer";
Santos Cordonfa5cf462017-04-05 10:37:00 -07003252 }
3253 return "unknown";
3254}
3255
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003256void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
3257 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003258 InputMapper::configure(when, config, changes);
3259
3260 mConfig = *config;
3261
3262 if (!changes) { // first time only
3263 // Configure basic parameters.
3264 configureParameters();
3265
3266 // Configure common accumulators.
3267 mCursorScrollAccumulator.configure(getDevice());
3268 mTouchButtonAccumulator.configure(getDevice());
3269
3270 // Configure absolute axis information.
3271 configureRawPointerAxes();
3272
3273 // Prepare input device calibration.
3274 parseCalibration();
3275 resolveCalibration();
3276 }
3277
Michael Wright842500e2015-03-13 17:32:02 -07003278 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
Jason Gerecke12d6baa2014-01-27 18:34:20 -08003279 // Update location calibration to reflect current settings
3280 updateAffineTransformation();
3281 }
3282
Michael Wrightd02c5b62014-02-10 15:10:22 -08003283 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
3284 // Update pointer speed.
3285 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
3286 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3287 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
3288 }
3289
3290 bool resetNeeded = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003291 if (!changes ||
3292 (changes &
3293 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
3294 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
3295 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
3296 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003297 // Configure device sources, surface dimensions, orientation and
3298 // scaling factors.
3299 configureSurface(when, &resetNeeded);
3300 }
3301
3302 if (changes && resetNeeded) {
3303 // Send reset, unless this is the first time the device has been configured,
3304 // in which case the reader will call reset itself after all mappers are ready.
3305 getDevice()->notifyReset(when);
3306 }
3307}
3308
Michael Wright842500e2015-03-13 17:32:02 -07003309void TouchInputMapper::resolveExternalStylusPresence() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003310 std::vector<InputDeviceInfo> devices;
Michael Wright842500e2015-03-13 17:32:02 -07003311 mContext->getExternalStylusDevices(devices);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003312 mExternalStylusConnected = !devices.empty();
Michael Wright842500e2015-03-13 17:32:02 -07003313
3314 if (!mExternalStylusConnected) {
3315 resetExternalStylus();
3316 }
3317}
3318
Michael Wrightd02c5b62014-02-10 15:10:22 -08003319void TouchInputMapper::configureParameters() {
3320 // Use the pointer presentation mode for devices that do not support distinct
3321 // multitouch. The spot-based presentation relies on being able to accurately
3322 // locate two or more fingers on the touch pad.
3323 mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT)
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003324 ? Parameters::GESTURE_MODE_SINGLE_TOUCH
3325 : Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003326
3327 String8 gestureModeString;
3328 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003329 gestureModeString)) {
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04003330 if (gestureModeString == "single-touch") {
3331 mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH;
3332 } else if (gestureModeString == "multi-touch") {
3333 mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003334 } else if (gestureModeString != "default") {
3335 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
3336 }
3337 }
3338
3339 if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) {
3340 // The device is a touch screen.
3341 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3342 } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) {
3343 // The device is a pointing device like a track pad.
3344 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003345 } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X) ||
3346 getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003347 // The device is a cursor device with a touch pad attached.
3348 // By default don't use the touch pad to move the pointer.
3349 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3350 } else {
3351 // The device is a touch pad of unknown purpose.
3352 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3353 }
3354
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003355 mParameters.hasButtonUnderPad =
Michael Wrightd02c5b62014-02-10 15:10:22 -08003356 getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD);
3357
3358 String8 deviceTypeString;
3359 if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003360 deviceTypeString)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003361 if (deviceTypeString == "touchScreen") {
3362 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3363 } else if (deviceTypeString == "touchPad") {
3364 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD;
3365 } else if (deviceTypeString == "touchNavigation") {
3366 mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION;
3367 } else if (deviceTypeString == "pointer") {
3368 mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER;
3369 } else if (deviceTypeString != "default") {
3370 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
3371 }
3372 }
3373
3374 mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN;
3375 getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003376 mParameters.orientationAware);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003377
3378 mParameters.hasAssociatedDisplay = false;
3379 mParameters.associatedDisplayIsExternal = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003380 if (mParameters.orientationAware ||
3381 mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN ||
3382 mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003383 mParameters.hasAssociatedDisplay = true;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003384 if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN) {
3385 mParameters.associatedDisplayIsExternal = getDevice()->isExternal();
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003386 String8 uniqueDisplayId;
Santos Cordonfa5cf462017-04-05 10:37:00 -07003387 getDevice()->getConfiguration().tryGetProperty(String8("touch.displayId"),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003388 uniqueDisplayId);
Siarhei Vishniakouec8f7252018-07-06 11:19:32 +01003389 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
Santos Cordonfa5cf462017-04-05 10:37:00 -07003390 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003391 }
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003392 if (getDevice()->getAssociatedDisplayPort()) {
3393 mParameters.hasAssociatedDisplay = true;
3394 }
Jeff Brownc5e24422014-02-26 18:48:51 -08003395
3396 // Initial downs on external touch devices should wake the device.
3397 // Normally we don't do this for internal touch screens to prevent them from waking
3398 // up in your pocket but you can enable it using the input device configuration.
3399 mParameters.wake = getDevice()->isExternal();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003400 getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003401}
3402
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003403void TouchInputMapper::dumpParameters(std::string& dump) {
3404 dump += INDENT3 "Parameters:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003405
3406 switch (mParameters.gestureMode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003407 case Parameters::GESTURE_MODE_SINGLE_TOUCH:
3408 dump += INDENT4 "GestureMode: single-touch\n";
3409 break;
3410 case Parameters::GESTURE_MODE_MULTI_TOUCH:
3411 dump += INDENT4 "GestureMode: multi-touch\n";
3412 break;
3413 default:
3414 assert(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003415 }
3416
3417 switch (mParameters.deviceType) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003418 case Parameters::DEVICE_TYPE_TOUCH_SCREEN:
3419 dump += INDENT4 "DeviceType: touchScreen\n";
3420 break;
3421 case Parameters::DEVICE_TYPE_TOUCH_PAD:
3422 dump += INDENT4 "DeviceType: touchPad\n";
3423 break;
3424 case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION:
3425 dump += INDENT4 "DeviceType: touchNavigation\n";
3426 break;
3427 case Parameters::DEVICE_TYPE_POINTER:
3428 dump += INDENT4 "DeviceType: pointer\n";
3429 break;
3430 default:
3431 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003432 }
3433
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003434 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
3435 "displayId='%s'\n",
3436 toString(mParameters.hasAssociatedDisplay),
3437 toString(mParameters.associatedDisplayIsExternal),
3438 mParameters.uniqueDisplayId.c_str());
3439 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Michael Wrightd02c5b62014-02-10 15:10:22 -08003440}
3441
3442void TouchInputMapper::configureRawPointerAxes() {
3443 mRawPointerAxes.clear();
3444}
3445
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003446void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
3447 dump += INDENT3 "Raw Touch Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003448 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
3449 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
3450 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
3451 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
3452 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
3453 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
3454 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
3455 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
3456 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
3457 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
3458 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
3459 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
3460 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
3461}
3462
Michael Wright842500e2015-03-13 17:32:02 -07003463bool TouchInputMapper::hasExternalStylus() const {
3464 return mExternalStylusConnected;
3465}
3466
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003467/**
3468 * Determine which DisplayViewport to use.
3469 * 1. If display port is specified, return the matching viewport. If matching viewport not
3470 * found, then return.
3471 * 2. If a device has associated display, get the matching viewport by either unique id or by
3472 * the display type (internal or external).
3473 * 3. Otherwise, use a non-display viewport.
3474 */
3475std::optional<DisplayViewport> TouchInputMapper::findViewport() {
3476 if (mParameters.hasAssociatedDisplay) {
3477 const std::optional<uint8_t> displayPort = mDevice->getAssociatedDisplayPort();
3478 if (displayPort) {
3479 // Find the viewport that contains the same port
Arthur Hung2c9a3342019-07-23 14:18:59 +08003480 return mDevice->getAssociatedViewport();
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003481 }
3482
Arthur Hung2c9a3342019-07-23 14:18:59 +08003483 // Check if uniqueDisplayId is specified in idc file.
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003484 if (!mParameters.uniqueDisplayId.empty()) {
3485 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
3486 }
3487
3488 ViewportType viewportTypeToUse;
3489 if (mParameters.associatedDisplayIsExternal) {
3490 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
3491 } else {
3492 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
3493 }
Arthur Hung41a712e2018-11-22 19:41:03 +08003494
3495 std::optional<DisplayViewport> viewport =
3496 mConfig.getDisplayViewportByType(viewportTypeToUse);
3497 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
3498 ALOGW("Input device %s should be associated with external display, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003499 "fallback to internal one for the external viewport is not found.",
3500 getDeviceName().c_str());
Arthur Hung41a712e2018-11-22 19:41:03 +08003501 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
3502 }
3503
3504 return viewport;
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003505 }
3506
Arthur Hung2c9a3342019-07-23 14:18:59 +08003507 // No associated display, return a non-display viewport.
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003508 DisplayViewport newViewport;
3509 // Raw width and height in the natural orientation.
3510 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3511 int32_t rawHeight = mRawPointerAxes.getRawHeight();
3512 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
3513 return std::make_optional(newViewport);
3514}
3515
Michael Wrightd02c5b62014-02-10 15:10:22 -08003516void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
3517 int32_t oldDeviceMode = mDeviceMode;
3518
Michael Wright842500e2015-03-13 17:32:02 -07003519 resolveExternalStylusPresence();
3520
Michael Wrightd02c5b62014-02-10 15:10:22 -08003521 // Determine device mode.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003522 if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER &&
3523 mConfig.pointerGesturesEnabled) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003524 mSource = AINPUT_SOURCE_MOUSE;
3525 mDeviceMode = DEVICE_MODE_POINTER;
3526 if (hasStylus()) {
3527 mSource |= AINPUT_SOURCE_STYLUS;
3528 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003529 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN &&
3530 mParameters.hasAssociatedDisplay) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003531 mSource = AINPUT_SOURCE_TOUCHSCREEN;
3532 mDeviceMode = DEVICE_MODE_DIRECT;
Michael Wright2f78b682015-06-12 15:25:08 +01003533 if (hasStylus()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003534 mSource |= AINPUT_SOURCE_STYLUS;
3535 }
Michael Wright2f78b682015-06-12 15:25:08 +01003536 if (hasExternalStylus()) {
3537 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
3538 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08003539 } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) {
3540 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
3541 mDeviceMode = DEVICE_MODE_NAVIGATION;
3542 } else {
3543 mSource = AINPUT_SOURCE_TOUCHPAD;
3544 mDeviceMode = DEVICE_MODE_UNSCALED;
3545 }
3546
3547 // Ensure we have valid X and Y axes.
3548 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003549 ALOGW("Touch device '%s' did not report support for X or Y axis! "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003550 "The device will be inoperable.",
3551 getDeviceName().c_str());
Michael Wrightd02c5b62014-02-10 15:10:22 -08003552 mDeviceMode = DEVICE_MODE_DISABLED;
3553 return;
3554 }
3555
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003556 // Get associated display dimensions.
3557 std::optional<DisplayViewport> newViewport = findViewport();
3558 if (!newViewport) {
3559 ALOGI("Touch device '%s' could not query the properties of its associated "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003560 "display. The device will be inoperable until the display size "
3561 "becomes available.",
3562 getDeviceName().c_str());
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003563 mDeviceMode = DEVICE_MODE_DISABLED;
3564 return;
3565 }
3566
Michael Wrightd02c5b62014-02-10 15:10:22 -08003567 // Raw width and height in the natural orientation.
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003568 int32_t rawWidth = mRawPointerAxes.getRawWidth();
3569 int32_t rawHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003570
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003571 bool viewportChanged = mViewport != *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003572 if (viewportChanged) {
Siarhei Vishniakou8158e7e2018-10-15 14:28:20 -07003573 mViewport = *newViewport;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003574
3575 if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) {
3576 // Convert rotated viewport to natural surface coordinates.
3577 int32_t naturalLogicalWidth, naturalLogicalHeight;
3578 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
3579 int32_t naturalPhysicalLeft, naturalPhysicalTop;
3580 int32_t naturalDeviceWidth, naturalDeviceHeight;
3581 switch (mViewport.orientation) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003582 case DISPLAY_ORIENTATION_90:
3583 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3584 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3585 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3586 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3587 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
3588 naturalPhysicalTop = mViewport.physicalLeft;
3589 naturalDeviceWidth = mViewport.deviceHeight;
3590 naturalDeviceHeight = mViewport.deviceWidth;
3591 break;
3592 case DISPLAY_ORIENTATION_180:
3593 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3594 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3595 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3596 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3597 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
3598 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
3599 naturalDeviceWidth = mViewport.deviceWidth;
3600 naturalDeviceHeight = mViewport.deviceHeight;
3601 break;
3602 case DISPLAY_ORIENTATION_270:
3603 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
3604 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
3605 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
3606 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
3607 naturalPhysicalLeft = mViewport.physicalTop;
3608 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
3609 naturalDeviceWidth = mViewport.deviceHeight;
3610 naturalDeviceHeight = mViewport.deviceWidth;
3611 break;
3612 case DISPLAY_ORIENTATION_0:
3613 default:
3614 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
3615 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
3616 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
3617 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
3618 naturalPhysicalLeft = mViewport.physicalLeft;
3619 naturalPhysicalTop = mViewport.physicalTop;
3620 naturalDeviceWidth = mViewport.deviceWidth;
3621 naturalDeviceHeight = mViewport.deviceHeight;
3622 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003623 }
3624
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003625 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
3626 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
3627 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
3628 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
3629 }
3630
Michael Wright358bcc72018-08-21 04:01:07 +01003631 mPhysicalWidth = naturalPhysicalWidth;
3632 mPhysicalHeight = naturalPhysicalHeight;
3633 mPhysicalLeft = naturalPhysicalLeft;
3634 mPhysicalTop = naturalPhysicalTop;
3635
Michael Wrightd02c5b62014-02-10 15:10:22 -08003636 mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
3637 mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
3638 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
3639 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
3640
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003641 mSurfaceOrientation =
3642 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003643 } else {
Michael Wright358bcc72018-08-21 04:01:07 +01003644 mPhysicalWidth = rawWidth;
3645 mPhysicalHeight = rawHeight;
3646 mPhysicalLeft = 0;
3647 mPhysicalTop = 0;
3648
Michael Wrightd02c5b62014-02-10 15:10:22 -08003649 mSurfaceWidth = rawWidth;
3650 mSurfaceHeight = rawHeight;
3651 mSurfaceLeft = 0;
3652 mSurfaceTop = 0;
3653 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
3654 }
3655 }
3656
3657 // If moving between pointer modes, need to reset some state.
3658 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
3659 if (deviceModeChanged) {
3660 mOrientedRanges.clear();
3661 }
3662
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003663 // Create or update pointer controller if needed.
Michael Wrightd02c5b62014-02-10 15:10:22 -08003664 if (mDeviceMode == DEVICE_MODE_POINTER ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003665 (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) {
Arthur Hungc7ad2d02018-12-18 17:41:29 +08003666 if (mPointerController == nullptr || viewportChanged) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003667 mPointerController = getPolicy()->obtainPointerController(getDeviceId());
3668 }
3669 } else {
3670 mPointerController.clear();
3671 }
3672
3673 if (viewportChanged || deviceModeChanged) {
3674 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003675 "display id %d",
3676 getDeviceId(), getDeviceName().c_str(), mSurfaceWidth, mSurfaceHeight,
3677 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003678
3679 // Configure X and Y factors.
3680 mXScale = float(mSurfaceWidth) / rawWidth;
3681 mYScale = float(mSurfaceHeight) / rawHeight;
3682 mXTranslate = -mSurfaceLeft;
3683 mYTranslate = -mSurfaceTop;
3684 mXPrecision = 1.0f / mXScale;
3685 mYPrecision = 1.0f / mYScale;
3686
3687 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
3688 mOrientedRanges.x.source = mSource;
3689 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
3690 mOrientedRanges.y.source = mSource;
3691
3692 configureVirtualKeys();
3693
3694 // Scale factor for terms that are not oriented in a particular axis.
3695 // If the pixels are square then xScale == yScale otherwise we fake it
3696 // by choosing an average.
3697 mGeometricScale = avg(mXScale, mYScale);
3698
3699 // Size of diagonal axis.
3700 float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight);
3701
3702 // Size factors.
3703 if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003704 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003705 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003706 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003707 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
3708 } else {
3709 mSizeScale = 0.0f;
3710 }
3711
3712 mOrientedRanges.haveTouchSize = true;
3713 mOrientedRanges.haveToolSize = true;
3714 mOrientedRanges.haveSize = true;
3715
3716 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
3717 mOrientedRanges.touchMajor.source = mSource;
3718 mOrientedRanges.touchMajor.min = 0;
3719 mOrientedRanges.touchMajor.max = diagonalSize;
3720 mOrientedRanges.touchMajor.flat = 0;
3721 mOrientedRanges.touchMajor.fuzz = 0;
3722 mOrientedRanges.touchMajor.resolution = 0;
3723
3724 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
3725 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
3726
3727 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
3728 mOrientedRanges.toolMajor.source = mSource;
3729 mOrientedRanges.toolMajor.min = 0;
3730 mOrientedRanges.toolMajor.max = diagonalSize;
3731 mOrientedRanges.toolMajor.flat = 0;
3732 mOrientedRanges.toolMajor.fuzz = 0;
3733 mOrientedRanges.toolMajor.resolution = 0;
3734
3735 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
3736 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
3737
3738 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
3739 mOrientedRanges.size.source = mSource;
3740 mOrientedRanges.size.min = 0;
3741 mOrientedRanges.size.max = 1.0;
3742 mOrientedRanges.size.flat = 0;
3743 mOrientedRanges.size.fuzz = 0;
3744 mOrientedRanges.size.resolution = 0;
3745 } else {
3746 mSizeScale = 0.0f;
3747 }
3748
3749 // Pressure factors.
3750 mPressureScale = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003751 float pressureMax = 1.0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003752 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL ||
3753 mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003754 if (mCalibration.havePressureScale) {
3755 mPressureScale = mCalibration.pressureScale;
Michael Wrightaa449c92017-12-13 21:21:43 +00003756 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003757 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003758 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
3759 }
3760 }
3761
3762 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
3763 mOrientedRanges.pressure.source = mSource;
3764 mOrientedRanges.pressure.min = 0;
Michael Wrightaa449c92017-12-13 21:21:43 +00003765 mOrientedRanges.pressure.max = pressureMax;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003766 mOrientedRanges.pressure.flat = 0;
3767 mOrientedRanges.pressure.fuzz = 0;
3768 mOrientedRanges.pressure.resolution = 0;
3769
3770 // Tilt
3771 mTiltXCenter = 0;
3772 mTiltXScale = 0;
3773 mTiltYCenter = 0;
3774 mTiltYScale = 0;
3775 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
3776 if (mHaveTilt) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003777 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
3778 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003779 mTiltXScale = M_PI / 180;
3780 mTiltYScale = M_PI / 180;
3781
3782 mOrientedRanges.haveTilt = true;
3783
3784 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
3785 mOrientedRanges.tilt.source = mSource;
3786 mOrientedRanges.tilt.min = 0;
3787 mOrientedRanges.tilt.max = M_PI_2;
3788 mOrientedRanges.tilt.flat = 0;
3789 mOrientedRanges.tilt.fuzz = 0;
3790 mOrientedRanges.tilt.resolution = 0;
3791 }
3792
3793 // Orientation
3794 mOrientationScale = 0;
3795 if (mHaveTilt) {
3796 mOrientedRanges.haveOrientation = true;
3797
3798 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3799 mOrientedRanges.orientation.source = mSource;
3800 mOrientedRanges.orientation.min = -M_PI;
3801 mOrientedRanges.orientation.max = M_PI;
3802 mOrientedRanges.orientation.flat = 0;
3803 mOrientedRanges.orientation.fuzz = 0;
3804 mOrientedRanges.orientation.resolution = 0;
3805 } else if (mCalibration.orientationCalibration !=
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003806 Calibration::ORIENTATION_CALIBRATION_NONE) {
3807 if (mCalibration.orientationCalibration ==
3808 Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003809 if (mRawPointerAxes.orientation.valid) {
3810 if (mRawPointerAxes.orientation.maxValue > 0) {
3811 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
3812 } else if (mRawPointerAxes.orientation.minValue < 0) {
3813 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
3814 } else {
3815 mOrientationScale = 0;
3816 }
3817 }
3818 }
3819
3820 mOrientedRanges.haveOrientation = true;
3821
3822 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
3823 mOrientedRanges.orientation.source = mSource;
3824 mOrientedRanges.orientation.min = -M_PI_2;
3825 mOrientedRanges.orientation.max = M_PI_2;
3826 mOrientedRanges.orientation.flat = 0;
3827 mOrientedRanges.orientation.fuzz = 0;
3828 mOrientedRanges.orientation.resolution = 0;
3829 }
3830
3831 // Distance
3832 mDistanceScale = 0;
3833 if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003834 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_SCALED) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08003835 if (mCalibration.haveDistanceScale) {
3836 mDistanceScale = mCalibration.distanceScale;
3837 } else {
3838 mDistanceScale = 1.0f;
3839 }
3840 }
3841
3842 mOrientedRanges.haveDistance = true;
3843
3844 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
3845 mOrientedRanges.distance.source = mSource;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003846 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
3847 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003848 mOrientedRanges.distance.flat = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003849 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003850 mOrientedRanges.distance.resolution = 0;
3851 }
3852
3853 // Compute oriented precision, scales and ranges.
3854 // Note that the maximum value reported is an inclusive maximum value so it is one
3855 // unit less than the total width or height of surface.
3856 switch (mSurfaceOrientation) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003857 case DISPLAY_ORIENTATION_90:
3858 case DISPLAY_ORIENTATION_270:
3859 mOrientedXPrecision = mYPrecision;
3860 mOrientedYPrecision = mXPrecision;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003861
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003862 mOrientedRanges.x.min = mYTranslate;
3863 mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1;
3864 mOrientedRanges.x.flat = 0;
3865 mOrientedRanges.x.fuzz = 0;
3866 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003867
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003868 mOrientedRanges.y.min = mXTranslate;
3869 mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1;
3870 mOrientedRanges.y.flat = 0;
3871 mOrientedRanges.y.fuzz = 0;
3872 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
3873 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003874
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003875 default:
3876 mOrientedXPrecision = mXPrecision;
3877 mOrientedYPrecision = mYPrecision;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003878
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003879 mOrientedRanges.x.min = mXTranslate;
3880 mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1;
3881 mOrientedRanges.x.flat = 0;
3882 mOrientedRanges.x.fuzz = 0;
3883 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003884
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003885 mOrientedRanges.y.min = mYTranslate;
3886 mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1;
3887 mOrientedRanges.y.flat = 0;
3888 mOrientedRanges.y.fuzz = 0;
3889 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
3890 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003891 }
3892
Jason Gerecke71b16e82014-03-10 09:47:59 -07003893 // Location
3894 updateAffineTransformation();
3895
Michael Wrightd02c5b62014-02-10 15:10:22 -08003896 if (mDeviceMode == DEVICE_MODE_POINTER) {
3897 // Compute pointer gesture detection parameters.
3898 float rawDiagonal = hypotf(rawWidth, rawHeight);
3899 float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight);
3900
3901 // Scale movements such that one whole swipe of the touch pad covers a
3902 // given area relative to the diagonal size of the display when no acceleration
3903 // is applied.
3904 // Assume that the touch pad has a square aspect ratio such that movements in
3905 // X and Y of the same number of raw units cover the same physical distance.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003906 mPointerXMovementScale =
3907 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003908 mPointerYMovementScale = mPointerXMovementScale;
3909
3910 // Scale zooms to cover a smaller range of the display than movements do.
3911 // This value determines the area around the pointer that is affected by freeform
3912 // pointer gestures.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003913 mPointerXZoomScale =
3914 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003915 mPointerYZoomScale = mPointerXZoomScale;
3916
3917 // Max width between pointers to detect a swipe gesture is more than some fraction
3918 // of the diagonal axis of the touch pad. Touches that are wider than this are
3919 // translated into freeform gestures.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003920 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003921
3922 // Abort current pointer usages because the state has changed.
3923 abortPointerUsage(when, 0 /*policyFlags*/);
3924 }
3925
3926 // Inform the dispatcher about the changes.
3927 *outResetNeeded = true;
3928 bumpGeneration();
3929 }
3930}
3931
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003932void TouchInputMapper::dumpSurface(std::string& dump) {
Siarhei Vishniakoud6343922018-07-06 23:33:37 +01003933 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003934 dump += StringPrintf(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth);
3935 dump += StringPrintf(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight);
3936 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
3937 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Michael Wright358bcc72018-08-21 04:01:07 +01003938 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
3939 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
3940 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
3941 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003942 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003943}
3944
3945void TouchInputMapper::configureVirtualKeys() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003946 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003947 getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions);
3948
3949 mVirtualKeys.clear();
3950
3951 if (virtualKeyDefinitions.size() == 0) {
3952 return;
3953 }
3954
Michael Wrightd02c5b62014-02-10 15:10:22 -08003955 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
3956 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
Siarhei Vishniakou26e34d92018-11-12 13:51:26 -08003957 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
3958 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
Michael Wrightd02c5b62014-02-10 15:10:22 -08003959
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003960 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
3961 VirtualKey virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003962
3963 virtualKey.scanCode = virtualKeyDefinition.scanCode;
3964 int32_t keyCode;
Dmitry Torokhov0faaa0b2015-09-24 13:13:55 -07003965 int32_t dummyKeyMetaState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08003966 uint32_t flags;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003967 if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0, &keyCode,
3968 &dummyKeyMetaState, &flags)) {
3969 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003970 continue; // drop the key
Michael Wrightd02c5b62014-02-10 15:10:22 -08003971 }
3972
3973 virtualKey.keyCode = keyCode;
3974 virtualKey.flags = flags;
3975
3976 // convert the key definition's display coordinates into touch coordinates for a hit box
3977 int32_t halfWidth = virtualKeyDefinition.width / 2;
3978 int32_t halfHeight = virtualKeyDefinition.height / 2;
3979
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07003980 virtualKey.hitLeft =
3981 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mSurfaceWidth +
3982 touchScreenLeft;
3983 virtualKey.hitRight =
3984 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mSurfaceWidth +
3985 touchScreenLeft;
3986 virtualKey.hitTop =
3987 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mSurfaceHeight +
3988 touchScreenTop;
3989 virtualKey.hitBottom =
3990 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mSurfaceHeight +
3991 touchScreenTop;
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003992 mVirtualKeys.push_back(virtualKey);
Michael Wrightd02c5b62014-02-10 15:10:22 -08003993 }
3994}
3995
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003996void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08003997 if (!mVirtualKeys.empty()) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08003998 dump += INDENT3 "Virtual Keys:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08003999
4000 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004001 const VirtualKey& virtualKey = mVirtualKeys[i];
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004002 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004003 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
4004 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
4005 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004006 }
4007 }
4008}
4009
4010void TouchInputMapper::parseCalibration() {
4011 const PropertyMap& in = getDevice()->getConfiguration();
4012 Calibration& out = mCalibration;
4013
4014 // Size
4015 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT;
4016 String8 sizeCalibrationString;
4017 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
4018 if (sizeCalibrationString == "none") {
4019 out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4020 } else if (sizeCalibrationString == "geometric") {
4021 out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4022 } else if (sizeCalibrationString == "diameter") {
4023 out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER;
4024 } else if (sizeCalibrationString == "box") {
4025 out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX;
4026 } else if (sizeCalibrationString == "area") {
4027 out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA;
4028 } else if (sizeCalibrationString != "default") {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004029 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004030 }
4031 }
4032
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004033 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
4034 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
4035 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004036
4037 // Pressure
4038 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT;
4039 String8 pressureCalibrationString;
4040 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
4041 if (pressureCalibrationString == "none") {
4042 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4043 } else if (pressureCalibrationString == "physical") {
4044 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4045 } else if (pressureCalibrationString == "amplitude") {
4046 out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE;
4047 } else if (pressureCalibrationString != "default") {
4048 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004049 pressureCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004050 }
4051 }
4052
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004053 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004054
4055 // Orientation
4056 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT;
4057 String8 orientationCalibrationString;
4058 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
4059 if (orientationCalibrationString == "none") {
4060 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4061 } else if (orientationCalibrationString == "interpolated") {
4062 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4063 } else if (orientationCalibrationString == "vector") {
4064 out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR;
4065 } else if (orientationCalibrationString != "default") {
4066 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004067 orientationCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004068 }
4069 }
4070
4071 // Distance
4072 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT;
4073 String8 distanceCalibrationString;
4074 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
4075 if (distanceCalibrationString == "none") {
4076 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4077 } else if (distanceCalibrationString == "scaled") {
4078 out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4079 } else if (distanceCalibrationString != "default") {
4080 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004081 distanceCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004082 }
4083 }
4084
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004085 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004086
4087 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT;
4088 String8 coverageCalibrationString;
4089 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
4090 if (coverageCalibrationString == "none") {
4091 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4092 } else if (coverageCalibrationString == "box") {
4093 out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX;
4094 } else if (coverageCalibrationString != "default") {
4095 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004096 coverageCalibrationString.string());
Michael Wrightd02c5b62014-02-10 15:10:22 -08004097 }
4098 }
4099}
4100
4101void TouchInputMapper::resolveCalibration() {
4102 // Size
4103 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
4104 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) {
4105 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC;
4106 }
4107 } else {
4108 mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE;
4109 }
4110
4111 // Pressure
4112 if (mRawPointerAxes.pressure.valid) {
4113 if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) {
4114 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL;
4115 }
4116 } else {
4117 mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE;
4118 }
4119
4120 // Orientation
4121 if (mRawPointerAxes.orientation.valid) {
4122 if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) {
4123 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED;
4124 }
4125 } else {
4126 mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE;
4127 }
4128
4129 // Distance
4130 if (mRawPointerAxes.distance.valid) {
4131 if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) {
4132 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED;
4133 }
4134 } else {
4135 mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE;
4136 }
4137
4138 // Coverage
4139 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) {
4140 mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE;
4141 }
4142}
4143
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004144void TouchInputMapper::dumpCalibration(std::string& dump) {
4145 dump += INDENT3 "Calibration:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08004146
4147 // Size
4148 switch (mCalibration.sizeCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004149 case Calibration::SIZE_CALIBRATION_NONE:
4150 dump += INDENT4 "touch.size.calibration: none\n";
4151 break;
4152 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4153 dump += INDENT4 "touch.size.calibration: geometric\n";
4154 break;
4155 case Calibration::SIZE_CALIBRATION_DIAMETER:
4156 dump += INDENT4 "touch.size.calibration: diameter\n";
4157 break;
4158 case Calibration::SIZE_CALIBRATION_BOX:
4159 dump += INDENT4 "touch.size.calibration: box\n";
4160 break;
4161 case Calibration::SIZE_CALIBRATION_AREA:
4162 dump += INDENT4 "touch.size.calibration: area\n";
4163 break;
4164 default:
4165 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004166 }
4167
4168 if (mCalibration.haveSizeScale) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004169 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004170 }
4171
4172 if (mCalibration.haveSizeBias) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004173 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004174 }
4175
4176 if (mCalibration.haveSizeIsSummed) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004177 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004178 toString(mCalibration.sizeIsSummed));
Michael Wrightd02c5b62014-02-10 15:10:22 -08004179 }
4180
4181 // Pressure
4182 switch (mCalibration.pressureCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004183 case Calibration::PRESSURE_CALIBRATION_NONE:
4184 dump += INDENT4 "touch.pressure.calibration: none\n";
4185 break;
4186 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
4187 dump += INDENT4 "touch.pressure.calibration: physical\n";
4188 break;
4189 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
4190 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
4191 break;
4192 default:
4193 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004194 }
4195
4196 if (mCalibration.havePressureScale) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004197 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004198 }
4199
4200 // Orientation
4201 switch (mCalibration.orientationCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004202 case Calibration::ORIENTATION_CALIBRATION_NONE:
4203 dump += INDENT4 "touch.orientation.calibration: none\n";
4204 break;
4205 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
4206 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
4207 break;
4208 case Calibration::ORIENTATION_CALIBRATION_VECTOR:
4209 dump += INDENT4 "touch.orientation.calibration: vector\n";
4210 break;
4211 default:
4212 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004213 }
4214
4215 // Distance
4216 switch (mCalibration.distanceCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004217 case Calibration::DISTANCE_CALIBRATION_NONE:
4218 dump += INDENT4 "touch.distance.calibration: none\n";
4219 break;
4220 case Calibration::DISTANCE_CALIBRATION_SCALED:
4221 dump += INDENT4 "touch.distance.calibration: scaled\n";
4222 break;
4223 default:
4224 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004225 }
4226
4227 if (mCalibration.haveDistanceScale) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004228 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004229 }
4230
4231 switch (mCalibration.coverageCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004232 case Calibration::COVERAGE_CALIBRATION_NONE:
4233 dump += INDENT4 "touch.coverage.calibration: none\n";
4234 break;
4235 case Calibration::COVERAGE_CALIBRATION_BOX:
4236 dump += INDENT4 "touch.coverage.calibration: box\n";
4237 break;
4238 default:
4239 ALOG_ASSERT(false);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004240 }
4241}
4242
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004243void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
4244 dump += INDENT3 "Affine Transformation:\n";
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004245
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08004246 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
4247 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
4248 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
4249 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
4250 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
4251 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
Jason Gereckeaf126fb2012-05-10 14:22:47 -07004252}
4253
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004254void TouchInputMapper::updateAffineTransformation() {
Jason Gerecke71b16e82014-03-10 09:47:59 -07004255 mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004256 mSurfaceOrientation);
Jason Gerecke12d6baa2014-01-27 18:34:20 -08004257}
4258
Michael Wrightd02c5b62014-02-10 15:10:22 -08004259void TouchInputMapper::reset(nsecs_t when) {
4260 mCursorButtonAccumulator.reset(getDevice());
4261 mCursorScrollAccumulator.reset(getDevice());
4262 mTouchButtonAccumulator.reset(getDevice());
4263
4264 mPointerVelocityControl.reset();
4265 mWheelXVelocityControl.reset();
4266 mWheelYVelocityControl.reset();
4267
Michael Wright842500e2015-03-13 17:32:02 -07004268 mRawStatesPending.clear();
4269 mCurrentRawState.clear();
4270 mCurrentCookedState.clear();
4271 mLastRawState.clear();
4272 mLastCookedState.clear();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004273 mPointerUsage = POINTER_USAGE_NONE;
4274 mSentHoverEnter = false;
Michael Wright842500e2015-03-13 17:32:02 -07004275 mHavePointerIds = false;
Michael Wright8e812822015-06-22 16:18:21 +01004276 mCurrentMotionAborted = false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004277 mDownTime = 0;
4278
4279 mCurrentVirtualKey.down = false;
4280
4281 mPointerGesture.reset();
4282 mPointerSimple.reset();
Michael Wright842500e2015-03-13 17:32:02 -07004283 resetExternalStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004284
Yi Kong9b14ac62018-07-17 13:48:38 -07004285 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004286 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4287 mPointerController->clearSpots();
4288 }
4289
4290 InputMapper::reset(when);
4291}
4292
Michael Wright842500e2015-03-13 17:32:02 -07004293void TouchInputMapper::resetExternalStylus() {
4294 mExternalStylusState.clear();
4295 mExternalStylusId = -1;
Michael Wright43fd19f2015-04-21 19:02:58 +01004296 mExternalStylusFusionTimeout = LLONG_MAX;
Michael Wright842500e2015-03-13 17:32:02 -07004297 mExternalStylusDataPending = false;
4298}
4299
Michael Wright43fd19f2015-04-21 19:02:58 +01004300void TouchInputMapper::clearStylusDataPendingFlags() {
4301 mExternalStylusDataPending = false;
4302 mExternalStylusFusionTimeout = LLONG_MAX;
4303}
4304
Michael Wrightd02c5b62014-02-10 15:10:22 -08004305void TouchInputMapper::process(const RawEvent* rawEvent) {
4306 mCursorButtonAccumulator.process(rawEvent);
4307 mCursorScrollAccumulator.process(rawEvent);
4308 mTouchButtonAccumulator.process(rawEvent);
4309
4310 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
4311 sync(rawEvent->when);
4312 }
4313}
4314
4315void TouchInputMapper::sync(nsecs_t when) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004316 const RawState* last =
4317 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004318
4319 // Push a new state.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004320 mRawStatesPending.emplace_back();
4321
4322 RawState* next = &mRawStatesPending.back();
Michael Wright842500e2015-03-13 17:32:02 -07004323 next->clear();
4324 next->when = when;
4325
Michael Wrightd02c5b62014-02-10 15:10:22 -08004326 // Sync button state.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004327 next->buttonState =
4328 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004329
Michael Wright842500e2015-03-13 17:32:02 -07004330 // Sync scroll
4331 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
4332 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Michael Wrightd02c5b62014-02-10 15:10:22 -08004333 mCursorScrollAccumulator.finishSync();
4334
Michael Wright842500e2015-03-13 17:32:02 -07004335 // Sync touch
4336 syncTouch(when, next);
4337
4338 // Assign pointer ids.
4339 if (!mHavePointerIds) {
4340 assignPointerIds(last, next);
4341 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08004342
4343#if DEBUG_RAW_EVENTS
Michael Wright842500e2015-03-13 17:32:02 -07004344 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004345 "hovering ids 0x%08x -> 0x%08x",
4346 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
4347 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
4348 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004349#endif
4350
Michael Wright842500e2015-03-13 17:32:02 -07004351 processRawTouches(false /*timeout*/);
4352}
Michael Wrightd02c5b62014-02-10 15:10:22 -08004353
Michael Wright842500e2015-03-13 17:32:02 -07004354void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004355 if (mDeviceMode == DEVICE_MODE_DISABLED) {
4356 // Drop all input if the device is disabled.
Michael Wright842500e2015-03-13 17:32:02 -07004357 mCurrentRawState.clear();
4358 mRawStatesPending.clear();
4359 return;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004360 }
4361
Michael Wright842500e2015-03-13 17:32:02 -07004362 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
4363 // valid and must go through the full cook and dispatch cycle. This ensures that anything
4364 // touching the current state will only observe the events that have been dispatched to the
4365 // rest of the pipeline.
4366 const size_t N = mRawStatesPending.size();
4367 size_t count;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004368 for (count = 0; count < N; count++) {
Michael Wright842500e2015-03-13 17:32:02 -07004369 const RawState& next = mRawStatesPending[count];
4370
4371 // A failure to assign the stylus id means that we're waiting on stylus data
4372 // and so should defer the rest of the pipeline.
4373 if (assignExternalStylusId(next, timeout)) {
4374 break;
4375 }
4376
4377 // All ready to go.
Michael Wright43fd19f2015-04-21 19:02:58 +01004378 clearStylusDataPendingFlags();
Michael Wright842500e2015-03-13 17:32:02 -07004379 mCurrentRawState.copyFrom(next);
Michael Wright43fd19f2015-04-21 19:02:58 +01004380 if (mCurrentRawState.when < mLastRawState.when) {
4381 mCurrentRawState.when = mLastRawState.when;
4382 }
Michael Wright842500e2015-03-13 17:32:02 -07004383 cookAndDispatch(mCurrentRawState.when);
4384 }
4385 if (count != 0) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08004386 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
Michael Wright842500e2015-03-13 17:32:02 -07004387 }
4388
Michael Wright842500e2015-03-13 17:32:02 -07004389 if (mExternalStylusDataPending) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004390 if (timeout) {
4391 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
4392 clearStylusDataPendingFlags();
4393 mCurrentRawState.copyFrom(mLastRawState);
4394#if DEBUG_STYLUS_FUSION
4395 ALOGD("Timeout expired, synthesizing event with new stylus data");
4396#endif
4397 cookAndDispatch(when);
4398 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
4399 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
4400 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
4401 }
Michael Wright842500e2015-03-13 17:32:02 -07004402 }
4403}
4404
4405void TouchInputMapper::cookAndDispatch(nsecs_t when) {
4406 // Always start with a clean state.
4407 mCurrentCookedState.clear();
4408
4409 // Apply stylus buttons to current raw state.
4410 applyExternalStylusButtonState(when);
4411
4412 // Handle policy on initial down or hover events.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004413 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
4414 mCurrentRawState.rawPointerData.pointerCount != 0;
Michael Wright842500e2015-03-13 17:32:02 -07004415
4416 uint32_t policyFlags = 0;
4417 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
4418 if (initialDown || buttonsPressed) {
4419 // If this is a touch screen, hide the pointer on an initial down.
4420 if (mDeviceMode == DEVICE_MODE_DIRECT) {
4421 getContext()->fadePointer();
4422 }
4423
4424 if (mParameters.wake) {
4425 policyFlags |= POLICY_FLAG_WAKE;
4426 }
4427 }
4428
4429 // Consume raw off-screen touches before cooking pointer data.
4430 // If touches are consumed, subsequent code will not receive any pointer data.
4431 if (consumeRawTouches(when, policyFlags)) {
4432 mCurrentRawState.rawPointerData.clear();
4433 }
4434
4435 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
4436 // with cooked pointer data that has the same ids and indices as the raw data.
4437 // The following code can use either the raw or cooked data, as needed.
4438 cookPointerData();
4439
4440 // Apply stylus pressure to current cooked state.
4441 applyExternalStylusTouchState(when);
4442
4443 // Synthesize key down from raw buttons if needed.
4444 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004445 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
4446 mCurrentCookedState.buttonState);
Michael Wright842500e2015-03-13 17:32:02 -07004447
4448 // Dispatch the touches either directly or by translation through a pointer on screen.
4449 if (mDeviceMode == DEVICE_MODE_POINTER) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004450 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
Michael Wright842500e2015-03-13 17:32:02 -07004451 uint32_t id = idBits.clearFirstMarkedBit();
4452 const RawPointerData::Pointer& pointer =
4453 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004454 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
4455 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
Michael Wright842500e2015-03-13 17:32:02 -07004456 mCurrentCookedState.stylusIdBits.markBit(id);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004457 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
4458 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Michael Wright842500e2015-03-13 17:32:02 -07004459 mCurrentCookedState.fingerIdBits.markBit(id);
4460 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
4461 mCurrentCookedState.mouseIdBits.markBit(id);
4462 }
4463 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004464 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
Michael Wright842500e2015-03-13 17:32:02 -07004465 uint32_t id = idBits.clearFirstMarkedBit();
4466 const RawPointerData::Pointer& pointer =
4467 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004468 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
4469 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
Michael Wright842500e2015-03-13 17:32:02 -07004470 mCurrentCookedState.stylusIdBits.markBit(id);
4471 }
4472 }
4473
4474 // Stylus takes precedence over all tools, then mouse, then finger.
4475 PointerUsage pointerUsage = mPointerUsage;
4476 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
4477 mCurrentCookedState.mouseIdBits.clear();
4478 mCurrentCookedState.fingerIdBits.clear();
4479 pointerUsage = POINTER_USAGE_STYLUS;
4480 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
4481 mCurrentCookedState.fingerIdBits.clear();
4482 pointerUsage = POINTER_USAGE_MOUSE;
4483 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004484 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright842500e2015-03-13 17:32:02 -07004485 pointerUsage = POINTER_USAGE_GESTURES;
4486 }
4487
4488 dispatchPointerUsage(when, policyFlags, pointerUsage);
4489 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004490 if (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches &&
4491 mPointerController != nullptr) {
Michael Wright842500e2015-03-13 17:32:02 -07004492 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT);
4493 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
4494
4495 mPointerController->setButtonState(mCurrentRawState.buttonState);
4496 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004497 mCurrentCookedState.cookedPointerData.idToIndex,
4498 mCurrentCookedState.cookedPointerData.touchingIdBits,
4499 mViewport.displayId);
Michael Wright842500e2015-03-13 17:32:02 -07004500 }
4501
Michael Wright8e812822015-06-22 16:18:21 +01004502 if (!mCurrentMotionAborted) {
4503 dispatchButtonRelease(when, policyFlags);
4504 dispatchHoverExit(when, policyFlags);
4505 dispatchTouches(when, policyFlags);
4506 dispatchHoverEnterAndMove(when, policyFlags);
4507 dispatchButtonPress(when, policyFlags);
4508 }
4509
4510 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4511 mCurrentMotionAborted = false;
4512 }
Michael Wright842500e2015-03-13 17:32:02 -07004513 }
4514
4515 // Synthesize key up from raw buttons if needed.
4516 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004517 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
4518 mCurrentCookedState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004519
4520 // Clear some transient state.
Michael Wright842500e2015-03-13 17:32:02 -07004521 mCurrentRawState.rawVScroll = 0;
4522 mCurrentRawState.rawHScroll = 0;
4523
4524 // Copy current touch to last touch in preparation for the next cycle.
4525 mLastRawState.copyFrom(mCurrentRawState);
4526 mLastCookedState.copyFrom(mCurrentCookedState);
4527}
4528
4529void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright7b159c92015-05-14 14:48:03 +01004530 if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Michael Wright842500e2015-03-13 17:32:02 -07004531 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
4532 }
4533}
4534
4535void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
Michael Wright53dca3a2015-04-23 17:39:53 +01004536 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
4537 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Michael Wright842500e2015-03-13 17:32:02 -07004538
Michael Wright53dca3a2015-04-23 17:39:53 +01004539 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
4540 float pressure = mExternalStylusState.pressure;
4541 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
4542 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
4543 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4544 }
4545 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
4546 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4547
4548 PointerProperties& properties =
4549 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
Michael Wright842500e2015-03-13 17:32:02 -07004550 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
4551 properties.toolType = mExternalStylusState.toolType;
4552 }
4553 }
4554}
4555
4556bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
4557 if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) {
4558 return false;
4559 }
4560
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004561 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
4562 state.rawPointerData.pointerCount != 0;
Michael Wright842500e2015-03-13 17:32:02 -07004563 if (initialDown) {
4564 if (mExternalStylusState.pressure != 0.0f) {
4565#if DEBUG_STYLUS_FUSION
4566 ALOGD("Have both stylus and touch data, beginning fusion");
4567#endif
4568 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
4569 } else if (timeout) {
4570#if DEBUG_STYLUS_FUSION
4571 ALOGD("Timeout expired, assuming touch is not a stylus.");
4572#endif
4573 resetExternalStylus();
4574 } else {
Michael Wright43fd19f2015-04-21 19:02:58 +01004575 if (mExternalStylusFusionTimeout == LLONG_MAX) {
4576 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
Michael Wright842500e2015-03-13 17:32:02 -07004577 }
4578#if DEBUG_STYLUS_FUSION
4579 ALOGD("No stylus data but stylus is connected, requesting timeout "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004580 "(%" PRId64 "ms)",
4581 mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004582#endif
Michael Wright43fd19f2015-04-21 19:02:58 +01004583 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004584 return true;
4585 }
4586 }
4587
4588 // Check if the stylus pointer has gone up.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004589 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
Michael Wright842500e2015-03-13 17:32:02 -07004590#if DEBUG_STYLUS_FUSION
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004591 ALOGD("Stylus pointer is going up");
Michael Wright842500e2015-03-13 17:32:02 -07004592#endif
4593 mExternalStylusId = -1;
4594 }
4595
4596 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004597}
4598
4599void TouchInputMapper::timeoutExpired(nsecs_t when) {
4600 if (mDeviceMode == DEVICE_MODE_POINTER) {
4601 if (mPointerUsage == POINTER_USAGE_GESTURES) {
4602 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
4603 }
Michael Wright842500e2015-03-13 17:32:02 -07004604 } else if (mDeviceMode == DEVICE_MODE_DIRECT) {
Michael Wright43fd19f2015-04-21 19:02:58 +01004605 if (mExternalStylusFusionTimeout < when) {
Michael Wright842500e2015-03-13 17:32:02 -07004606 processRawTouches(true /*timeout*/);
Michael Wright43fd19f2015-04-21 19:02:58 +01004607 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
4608 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
Michael Wright842500e2015-03-13 17:32:02 -07004609 }
4610 }
4611}
4612
4613void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
Michael Wright4af18b92015-04-20 22:03:54 +01004614 mExternalStylusState.copyFrom(state);
Michael Wright43fd19f2015-04-21 19:02:58 +01004615 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
Michael Wright842500e2015-03-13 17:32:02 -07004616 // We're either in the middle of a fused stream of data or we're waiting on data before
4617 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
4618 // data.
Michael Wright842500e2015-03-13 17:32:02 -07004619 mExternalStylusDataPending = true;
Michael Wright842500e2015-03-13 17:32:02 -07004620 processRawTouches(false /*timeout*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004621 }
4622}
4623
4624bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
4625 // Check for release of a virtual key.
4626 if (mCurrentVirtualKey.down) {
Michael Wright842500e2015-03-13 17:32:02 -07004627 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004628 // Pointer went up while virtual key was down.
4629 mCurrentVirtualKey.down = false;
4630 if (!mCurrentVirtualKey.ignored) {
4631#if DEBUG_VIRTUAL_KEYS
4632 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004633 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004634#endif
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004635 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
4636 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004637 }
4638 return true;
4639 }
4640
Michael Wright842500e2015-03-13 17:32:02 -07004641 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
4642 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4643 const RawPointerData::Pointer& pointer =
4644 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004645 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4646 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
4647 // Pointer is still within the space of the virtual key.
4648 return true;
4649 }
4650 }
4651
4652 // Pointer left virtual key area or another pointer also went down.
4653 // Send key cancellation but do not consume the touch yet.
4654 // This is useful when the user swipes through from the virtual key area
4655 // into the main display surface.
4656 mCurrentVirtualKey.down = false;
4657 if (!mCurrentVirtualKey.ignored) {
4658#if DEBUG_VIRTUAL_KEYS
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004659 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
4660 mCurrentVirtualKey.scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004661#endif
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004662 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
4663 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
4664 AKEY_EVENT_FLAG_CANCELED);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004665 }
4666 }
4667
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004668 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
4669 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004670 // Pointer just went down. Check for virtual key press or off-screen touches.
Michael Wright842500e2015-03-13 17:32:02 -07004671 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
4672 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004673 if (!isPointInsideSurface(pointer.x, pointer.y)) {
4674 // If exactly one pointer went down, check for virtual key hit.
4675 // Otherwise we will drop the entire stroke.
Michael Wright842500e2015-03-13 17:32:02 -07004676 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004677 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
4678 if (virtualKey) {
4679 mCurrentVirtualKey.down = true;
4680 mCurrentVirtualKey.downTime = when;
4681 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
4682 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004683 mCurrentVirtualKey.ignored =
4684 mContext->shouldDropVirtualKey(when, getDevice(), virtualKey->keyCode,
4685 virtualKey->scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004686
4687 if (!mCurrentVirtualKey.ignored) {
4688#if DEBUG_VIRTUAL_KEYS
4689 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004690 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004691#endif
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004692 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
4693 AKEY_EVENT_FLAG_FROM_SYSTEM |
4694 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004695 }
4696 }
4697 }
4698 return true;
4699 }
4700 }
4701
4702 // Disable all virtual key touches that happen within a short time interval of the
4703 // most recent touch within the screen area. The idea is to filter out stray
4704 // virtual key presses when interacting with the touch screen.
4705 //
4706 // Problems we're trying to solve:
4707 //
4708 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
4709 // virtual key area that is implemented by a separate touch panel and accidentally
4710 // triggers a virtual key.
4711 //
4712 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
4713 // area and accidentally triggers a virtual key. This often happens when virtual keys
4714 // are layed out below the screen near to where the on screen keyboard's space bar
4715 // is displayed.
Michael Wright842500e2015-03-13 17:32:02 -07004716 if (mConfig.virtualKeyQuietTime > 0 &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004717 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004718 mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
4719 }
4720 return false;
4721}
4722
4723void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004724 int32_t keyEventAction, int32_t keyEventFlags) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004725 int32_t keyCode = mCurrentVirtualKey.keyCode;
4726 int32_t scanCode = mCurrentVirtualKey.scanCode;
4727 nsecs_t downTime = mCurrentVirtualKey.downTime;
4728 int32_t metaState = mContext->getGlobalMetaState();
4729 policyFlags |= POLICY_FLAG_VIRTUAL;
4730
Prabir Pradhan42611e02018-11-27 14:04:02 -08004731 NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004732 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
4733 scanCode, metaState, downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004734 getListener()->notifyKey(&args);
4735}
4736
Michael Wright8e812822015-06-22 16:18:21 +01004737void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
4738 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4739 if (!currentIdBits.isEmpty()) {
4740 int32_t metaState = getContext()->getGlobalMetaState();
4741 int32_t buttonState = mCurrentCookedState.buttonState;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004742 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
4743 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4744 mCurrentCookedState.cookedPointerData.pointerProperties,
4745 mCurrentCookedState.cookedPointerData.pointerCoords,
4746 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
4747 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wright8e812822015-06-22 16:18:21 +01004748 mCurrentMotionAborted = true;
4749 }
4750}
4751
Michael Wrightd02c5b62014-02-10 15:10:22 -08004752void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
Michael Wright842500e2015-03-13 17:32:02 -07004753 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
4754 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004755 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01004756 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004757
4758 if (currentIdBits == lastIdBits) {
4759 if (!currentIdBits.isEmpty()) {
4760 // No pointer id changes so this is a move event.
4761 // The listener takes care of batching moves so we don't have to deal with that here.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004762 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
4763 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
4764 mCurrentCookedState.cookedPointerData.pointerProperties,
4765 mCurrentCookedState.cookedPointerData.pointerCoords,
4766 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
4767 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004768 }
4769 } else {
4770 // There may be pointers going up and pointers going down and pointers moving
4771 // all at the same time.
4772 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
4773 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
4774 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
4775 BitSet32 dispatchedIdBits(lastIdBits.value);
4776
4777 // Update last coordinates of pointers that have moved so that we observe the new
4778 // pointer positions at the same time as other pointers that have just gone up.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004779 bool moveNeeded =
4780 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
4781 mCurrentCookedState.cookedPointerData.pointerCoords,
4782 mCurrentCookedState.cookedPointerData.idToIndex,
4783 mLastCookedState.cookedPointerData.pointerProperties,
4784 mLastCookedState.cookedPointerData.pointerCoords,
4785 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01004786 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004787 moveNeeded = true;
4788 }
4789
4790 // Dispatch pointer up events.
4791 while (!upIdBits.isEmpty()) {
4792 uint32_t upId = upIdBits.clearFirstMarkedBit();
4793
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004794 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
4795 metaState, buttonState, 0,
4796 mLastCookedState.cookedPointerData.pointerProperties,
4797 mLastCookedState.cookedPointerData.pointerCoords,
4798 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
4799 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004800 dispatchedIdBits.clearBit(upId);
4801 }
4802
4803 // Dispatch move events if any of the remaining pointers moved from their old locations.
4804 // Although applications receive new locations as part of individual pointer up
4805 // events, they do not generally handle them except when presented in a move event.
Michael Wright43fd19f2015-04-21 19:02:58 +01004806 if (moveNeeded && !moveIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004807 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004808 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
4809 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
4810 mCurrentCookedState.cookedPointerData.pointerCoords,
4811 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
4812 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004813 }
4814
4815 // Dispatch pointer down events using the new pointer locations.
4816 while (!downIdBits.isEmpty()) {
4817 uint32_t downId = downIdBits.clearFirstMarkedBit();
4818 dispatchedIdBits.markBit(downId);
4819
4820 if (dispatchedIdBits.count() == 1) {
4821 // First pointer is going down. Set down time.
4822 mDownTime = when;
4823 }
4824
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004825 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
4826 metaState, buttonState, 0,
4827 mCurrentCookedState.cookedPointerData.pointerProperties,
4828 mCurrentCookedState.cookedPointerData.pointerCoords,
4829 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
4830 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004831 }
4832 }
4833}
4834
4835void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
4836 if (mSentHoverEnter &&
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004837 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
4838 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004839 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004840 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
4841 mLastCookedState.buttonState, 0,
4842 mLastCookedState.cookedPointerData.pointerProperties,
4843 mLastCookedState.cookedPointerData.pointerCoords,
4844 mLastCookedState.cookedPointerData.idToIndex,
4845 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
4846 mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004847 mSentHoverEnter = false;
4848 }
4849}
4850
4851void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004852 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
4853 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08004854 int32_t metaState = getContext()->getGlobalMetaState();
4855 if (!mSentHoverEnter) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004856 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
4857 metaState, mCurrentRawState.buttonState, 0,
4858 mCurrentCookedState.cookedPointerData.pointerProperties,
4859 mCurrentCookedState.cookedPointerData.pointerCoords,
4860 mCurrentCookedState.cookedPointerData.idToIndex,
4861 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4862 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004863 mSentHoverEnter = true;
4864 }
4865
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004866 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
4867 mCurrentRawState.buttonState, 0,
4868 mCurrentCookedState.cookedPointerData.pointerProperties,
4869 mCurrentCookedState.cookedPointerData.pointerCoords,
4870 mCurrentCookedState.cookedPointerData.idToIndex,
4871 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
4872 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08004873 }
4874}
4875
Michael Wright7b159c92015-05-14 14:48:03 +01004876void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
4877 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
4878 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
4879 const int32_t metaState = getContext()->getGlobalMetaState();
4880 int32_t buttonState = mLastCookedState.buttonState;
4881 while (!releasedButtons.isEmpty()) {
4882 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
4883 buttonState &= ~actionButton;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004884 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
4885 actionButton, 0, metaState, buttonState, 0,
4886 mCurrentCookedState.cookedPointerData.pointerProperties,
4887 mCurrentCookedState.cookedPointerData.pointerCoords,
4888 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4889 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wright7b159c92015-05-14 14:48:03 +01004890 }
4891}
4892
4893void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
4894 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
4895 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
4896 const int32_t metaState = getContext()->getGlobalMetaState();
4897 int32_t buttonState = mLastCookedState.buttonState;
4898 while (!pressedButtons.isEmpty()) {
4899 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
4900 buttonState |= actionButton;
4901 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004902 0, metaState, buttonState, 0,
4903 mCurrentCookedState.cookedPointerData.pointerProperties,
4904 mCurrentCookedState.cookedPointerData.pointerCoords,
4905 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
4906 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
Michael Wright7b159c92015-05-14 14:48:03 +01004907 }
4908}
4909
4910const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
4911 if (!cookedPointerData.touchingIdBits.isEmpty()) {
4912 return cookedPointerData.touchingIdBits;
4913 }
4914 return cookedPointerData.hoveringIdBits;
4915}
4916
Michael Wrightd02c5b62014-02-10 15:10:22 -08004917void TouchInputMapper::cookPointerData() {
Michael Wright842500e2015-03-13 17:32:02 -07004918 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004919
Michael Wright842500e2015-03-13 17:32:02 -07004920 mCurrentCookedState.cookedPointerData.clear();
4921 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
4922 mCurrentCookedState.cookedPointerData.hoveringIdBits =
4923 mCurrentRawState.rawPointerData.hoveringIdBits;
4924 mCurrentCookedState.cookedPointerData.touchingIdBits =
4925 mCurrentRawState.rawPointerData.touchingIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08004926
Michael Wright7b159c92015-05-14 14:48:03 +01004927 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
4928 mCurrentCookedState.buttonState = 0;
4929 } else {
4930 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
4931 }
4932
Michael Wrightd02c5b62014-02-10 15:10:22 -08004933 // Walk through the the active pointers and map device coordinates onto
4934 // surface coordinates and adjust for display orientation.
4935 for (uint32_t i = 0; i < currentPointerCount; i++) {
Michael Wright842500e2015-03-13 17:32:02 -07004936 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08004937
4938 // Size
4939 float touchMajor, touchMinor, toolMajor, toolMinor, size;
4940 switch (mCalibration.sizeCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07004941 case Calibration::SIZE_CALIBRATION_GEOMETRIC:
4942 case Calibration::SIZE_CALIBRATION_DIAMETER:
4943 case Calibration::SIZE_CALIBRATION_BOX:
4944 case Calibration::SIZE_CALIBRATION_AREA:
4945 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
4946 touchMajor = in.touchMajor;
4947 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4948 toolMajor = in.toolMajor;
4949 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4950 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
4951 : in.touchMajor;
4952 } else if (mRawPointerAxes.touchMajor.valid) {
4953 toolMajor = touchMajor = in.touchMajor;
4954 toolMinor = touchMinor =
4955 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
4956 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
4957 : in.touchMajor;
4958 } else if (mRawPointerAxes.toolMajor.valid) {
4959 touchMajor = toolMajor = in.toolMajor;
4960 touchMinor = toolMinor =
4961 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
4962 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
4963 : in.toolMajor;
4964 } else {
4965 ALOG_ASSERT(false,
4966 "No touch or tool axes. "
4967 "Size calibration should have been resolved to NONE.");
4968 touchMajor = 0;
4969 touchMinor = 0;
4970 toolMajor = 0;
4971 toolMinor = 0;
4972 size = 0;
4973 }
4974
4975 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
4976 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
4977 if (touchingCount > 1) {
4978 touchMajor /= touchingCount;
4979 touchMinor /= touchingCount;
4980 toolMajor /= touchingCount;
4981 toolMinor /= touchingCount;
4982 size /= touchingCount;
4983 }
4984 }
4985
4986 if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) {
4987 touchMajor *= mGeometricScale;
4988 touchMinor *= mGeometricScale;
4989 toolMajor *= mGeometricScale;
4990 toolMinor *= mGeometricScale;
4991 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) {
4992 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
4993 touchMinor = touchMajor;
4994 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
4995 toolMinor = toolMajor;
4996 } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) {
4997 touchMinor = touchMajor;
4998 toolMinor = toolMajor;
4999 }
5000
5001 mCalibration.applySizeScaleAndBias(&touchMajor);
5002 mCalibration.applySizeScaleAndBias(&touchMinor);
5003 mCalibration.applySizeScaleAndBias(&toolMajor);
5004 mCalibration.applySizeScaleAndBias(&toolMinor);
5005 size *= mSizeScale;
5006 break;
5007 default:
Michael Wrightd02c5b62014-02-10 15:10:22 -08005008 touchMajor = 0;
5009 touchMinor = 0;
5010 toolMajor = 0;
5011 toolMinor = 0;
5012 size = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005013 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005014 }
5015
5016 // Pressure
5017 float pressure;
5018 switch (mCalibration.pressureCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005019 case Calibration::PRESSURE_CALIBRATION_PHYSICAL:
5020 case Calibration::PRESSURE_CALIBRATION_AMPLITUDE:
5021 pressure = in.pressure * mPressureScale;
5022 break;
5023 default:
5024 pressure = in.isHovering ? 0 : 1;
5025 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005026 }
5027
5028 // Tilt and Orientation
5029 float tilt;
5030 float orientation;
5031 if (mHaveTilt) {
5032 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
5033 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
5034 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
5035 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
5036 } else {
5037 tilt = 0;
5038
5039 switch (mCalibration.orientationCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005040 case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED:
5041 orientation = in.orientation * mOrientationScale;
5042 break;
5043 case Calibration::ORIENTATION_CALIBRATION_VECTOR: {
5044 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
5045 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
5046 if (c1 != 0 || c2 != 0) {
5047 orientation = atan2f(c1, c2) * 0.5f;
5048 float confidence = hypotf(c1, c2);
5049 float scale = 1.0f + confidence / 16.0f;
5050 touchMajor *= scale;
5051 touchMinor /= scale;
5052 toolMajor *= scale;
5053 toolMinor /= scale;
5054 } else {
5055 orientation = 0;
5056 }
5057 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005058 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005059 default:
5060 orientation = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005061 }
5062 }
5063
5064 // Distance
5065 float distance;
5066 switch (mCalibration.distanceCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005067 case Calibration::DISTANCE_CALIBRATION_SCALED:
5068 distance = in.distance * mDistanceScale;
5069 break;
5070 default:
5071 distance = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005072 }
5073
5074 // Coverage
5075 int32_t rawLeft, rawTop, rawRight, rawBottom;
5076 switch (mCalibration.coverageCalibration) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005077 case Calibration::COVERAGE_CALIBRATION_BOX:
5078 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
5079 rawRight = in.toolMinor & 0x0000ffff;
5080 rawBottom = in.toolMajor & 0x0000ffff;
5081 rawTop = (in.toolMajor & 0xffff0000) >> 16;
5082 break;
5083 default:
5084 rawLeft = rawTop = rawRight = rawBottom = 0;
5085 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005086 }
5087
Jason Gereckeaf126fb2012-05-10 14:22:47 -07005088 // Adjust X,Y coords for device calibration
5089 // TODO: Adjust coverage coords?
5090 float xTransformed = in.x, yTransformed = in.y;
5091 mAffineTransform.applyTo(xTransformed, yTransformed);
5092
5093 // Adjust X, Y, and coverage coords for surface orientation.
5094 float x, y;
5095 float left, top, right, bottom;
5096
Michael Wrightd02c5b62014-02-10 15:10:22 -08005097 switch (mSurfaceOrientation) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005098 case DISPLAY_ORIENTATION_90:
5099 x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5100 y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate;
5101 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5102 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5103 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
5104 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
5105 orientation -= M_PI_2;
5106 if (mOrientedRanges.haveOrientation &&
5107 orientation < mOrientedRanges.orientation.min) {
5108 orientation +=
5109 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5110 }
5111 break;
5112 case DISPLAY_ORIENTATION_180:
5113 x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale;
5114 y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate;
5115 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
5116 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
5117 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
5118 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
5119 orientation -= M_PI;
5120 if (mOrientedRanges.haveOrientation &&
5121 orientation < mOrientedRanges.orientation.min) {
5122 orientation +=
5123 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5124 }
5125 break;
5126 case DISPLAY_ORIENTATION_270:
5127 x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale;
5128 y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5129 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
5130 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
5131 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5132 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5133 orientation += M_PI_2;
5134 if (mOrientedRanges.haveOrientation &&
5135 orientation > mOrientedRanges.orientation.max) {
5136 orientation -=
5137 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
5138 }
5139 break;
5140 default:
5141 x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5142 y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5143 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5144 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
5145 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5146 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
5147 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005148 }
5149
5150 // Write output coords.
Michael Wright842500e2015-03-13 17:32:02 -07005151 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005152 out.clear();
5153 out.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5154 out.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5155 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
5156 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
5157 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
5158 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
5159 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
5160 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
5161 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
5162 if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) {
5163 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
5164 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
5165 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
5166 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
5167 } else {
5168 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
5169 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
5170 }
5171
5172 // Write output properties.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005173 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Michael Wrightd02c5b62014-02-10 15:10:22 -08005174 uint32_t id = in.id;
5175 properties.clear();
5176 properties.id = id;
5177 properties.toolType = in.toolType;
5178
5179 // Write id index.
Michael Wright842500e2015-03-13 17:32:02 -07005180 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005181 }
5182}
5183
5184void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005185 PointerUsage pointerUsage) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005186 if (pointerUsage != mPointerUsage) {
5187 abortPointerUsage(when, policyFlags);
5188 mPointerUsage = pointerUsage;
5189 }
5190
5191 switch (mPointerUsage) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005192 case POINTER_USAGE_GESTURES:
5193 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
5194 break;
5195 case POINTER_USAGE_STYLUS:
5196 dispatchPointerStylus(when, policyFlags);
5197 break;
5198 case POINTER_USAGE_MOUSE:
5199 dispatchPointerMouse(when, policyFlags);
5200 break;
5201 default:
5202 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005203 }
5204}
5205
5206void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
5207 switch (mPointerUsage) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005208 case POINTER_USAGE_GESTURES:
5209 abortPointerGestures(when, policyFlags);
5210 break;
5211 case POINTER_USAGE_STYLUS:
5212 abortPointerStylus(when, policyFlags);
5213 break;
5214 case POINTER_USAGE_MOUSE:
5215 abortPointerMouse(when, policyFlags);
5216 break;
5217 default:
5218 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005219 }
5220
5221 mPointerUsage = POINTER_USAGE_NONE;
5222}
5223
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005224void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005225 // Update current gesture coordinates.
5226 bool cancelPreviousGesture, finishPreviousGesture;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005227 bool sendEvents =
5228 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005229 if (!sendEvents) {
5230 return;
5231 }
5232 if (finishPreviousGesture) {
5233 cancelPreviousGesture = false;
5234 }
5235
5236 // Update the pointer presentation and spots.
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005237 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5238 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005239 if (finishPreviousGesture || cancelPreviousGesture) {
5240 mPointerController->clearSpots();
5241 }
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005242
5243 if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
5244 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005245 mPointerGesture.currentGestureIdToIndex,
5246 mPointerGesture.currentGestureIdBits,
5247 mPointerController->getDisplayId());
Amirhossein Simjour3dd617b2015-10-09 10:39:48 -04005248 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08005249 } else {
5250 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
5251 }
5252
5253 // Show or hide the pointer if needed.
5254 switch (mPointerGesture.currentGestureMode) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005255 case PointerGesture::NEUTRAL:
5256 case PointerGesture::QUIET:
5257 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH &&
5258 mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) {
5259 // Remind the user of where the pointer is after finishing a gesture with spots.
5260 mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL);
5261 }
5262 break;
5263 case PointerGesture::TAP:
5264 case PointerGesture::TAP_DRAG:
5265 case PointerGesture::BUTTON_CLICK_OR_DRAG:
5266 case PointerGesture::HOVER:
5267 case PointerGesture::PRESS:
5268 case PointerGesture::SWIPE:
5269 // Unfade the pointer when the current gesture manipulates the
5270 // area directly under the pointer.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005271 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005272 break;
5273 case PointerGesture::FREEFORM:
5274 // Fade the pointer when the current gesture manipulates a different
5275 // area and there are spots to guide the user experience.
5276 if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) {
5277 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5278 } else {
5279 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
5280 }
5281 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005282 }
5283
5284 // Send events!
5285 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright7b159c92015-05-14 14:48:03 +01005286 int32_t buttonState = mCurrentCookedState.buttonState;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005287
5288 // Update last coordinates of pointers that have moved so that we observe the new
5289 // pointer positions at the same time as other pointers that have just gone up.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005290 bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP ||
5291 mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG ||
5292 mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG ||
5293 mPointerGesture.currentGestureMode == PointerGesture::PRESS ||
5294 mPointerGesture.currentGestureMode == PointerGesture::SWIPE ||
5295 mPointerGesture.currentGestureMode == PointerGesture::FREEFORM;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005296 bool moveNeeded = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005297 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
5298 !mPointerGesture.lastGestureIdBits.isEmpty() &&
5299 !mPointerGesture.currentGestureIdBits.isEmpty()) {
5300 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
5301 mPointerGesture.lastGestureIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005302 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005303 mPointerGesture.currentGestureCoords,
5304 mPointerGesture.currentGestureIdToIndex,
5305 mPointerGesture.lastGestureProperties,
5306 mPointerGesture.lastGestureCoords,
5307 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
Michael Wright7b159c92015-05-14 14:48:03 +01005308 if (buttonState != mLastCookedState.buttonState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005309 moveNeeded = true;
5310 }
5311 }
5312
5313 // Send motion events for all pointers that went up or were canceled.
5314 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
5315 if (!dispatchedGestureIdBits.isEmpty()) {
5316 if (cancelPreviousGesture) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005317 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5318 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5319 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5320 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5321 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005322
5323 dispatchedGestureIdBits.clear();
5324 } else {
5325 BitSet32 upGestureIdBits;
5326 if (finishPreviousGesture) {
5327 upGestureIdBits = dispatchedGestureIdBits;
5328 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005329 upGestureIdBits.value =
5330 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005331 }
5332 while (!upGestureIdBits.isEmpty()) {
5333 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
5334
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005335 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
5336 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5337 mPointerGesture.lastGestureProperties,
5338 mPointerGesture.lastGestureCoords,
5339 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
5340 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005341
5342 dispatchedGestureIdBits.clearBit(id);
5343 }
5344 }
5345 }
5346
5347 // Send motion events for all pointers that moved.
5348 if (moveNeeded) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005349 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
5350 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5351 mPointerGesture.currentGestureProperties,
5352 mPointerGesture.currentGestureCoords,
5353 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
5354 mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005355 }
5356
5357 // Send motion events for all pointers that went down.
5358 if (down) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005359 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
5360 ~dispatchedGestureIdBits.value);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005361 while (!downGestureIdBits.isEmpty()) {
5362 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
5363 dispatchedGestureIdBits.markBit(id);
5364
5365 if (dispatchedGestureIdBits.count() == 1) {
5366 mPointerGesture.downTime = when;
5367 }
5368
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005369 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
5370 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
5371 mPointerGesture.currentGestureCoords,
5372 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
5373 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005374 }
5375 }
5376
5377 // Send motion events for hover.
5378 if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) {
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005379 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
5380 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5381 mPointerGesture.currentGestureProperties,
5382 mPointerGesture.currentGestureCoords,
5383 mPointerGesture.currentGestureIdToIndex,
5384 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005385 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005386 // Synthesize a hover move event after all pointers go up to indicate that
5387 // the pointer is hovering again even if the user is not currently touching
5388 // the touch pad. This ensures that a view will receive a fresh hover enter
5389 // event after a tap.
5390 float x, y;
5391 mPointerController->getPosition(&x, &y);
5392
5393 PointerProperties pointerProperties;
5394 pointerProperties.clear();
5395 pointerProperties.id = 0;
5396 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5397
5398 PointerCoords pointerCoords;
5399 pointerCoords.clear();
5400 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
5401 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5402
Arthur Hungc7ad2d02018-12-18 17:41:29 +08005403 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tan00f511d2019-06-12 16:55:40 -07005404 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
5405 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
5406 metaState, buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005407 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
5408 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08005409 getListener()->notifyMotion(&args);
5410 }
5411
5412 // Update state.
5413 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
5414 if (!down) {
5415 mPointerGesture.lastGestureIdBits.clear();
5416 } else {
5417 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005418 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005419 uint32_t id = idBits.clearFirstMarkedBit();
5420 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
5421 mPointerGesture.lastGestureProperties[index].copyFrom(
5422 mPointerGesture.currentGestureProperties[index]);
5423 mPointerGesture.lastGestureCoords[index].copyFrom(
5424 mPointerGesture.currentGestureCoords[index]);
5425 mPointerGesture.lastGestureIdToIndex[id] = index;
5426 }
5427 }
5428}
5429
5430void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
5431 // Cancel previously dispatches pointers.
5432 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
5433 int32_t metaState = getContext()->getGlobalMetaState();
Michael Wright842500e2015-03-13 17:32:02 -07005434 int32_t buttonState = mCurrentRawState.buttonState;
Atif Niyaz21da0ff2019-06-28 13:22:51 -07005435 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
5436 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
5437 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
5438 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
5439 0, 0, mPointerGesture.downTime);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005440 }
5441
5442 // Reset the current pointer gesture.
5443 mPointerGesture.reset();
5444 mPointerVelocityControl.reset();
5445
5446 // Remove any current spots.
Yi Kong9b14ac62018-07-17 13:48:38 -07005447 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005448 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
5449 mPointerController->clearSpots();
5450 }
5451}
5452
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005453bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
5454 bool* outFinishPreviousGesture, bool isTimeout) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005455 *outCancelPreviousGesture = false;
5456 *outFinishPreviousGesture = false;
5457
5458 // Handle TAP timeout.
5459 if (isTimeout) {
5460#if DEBUG_GESTURES
5461 ALOGD("Gestures: Processing timeout");
5462#endif
5463
5464 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5465 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5466 // The tap/drag timeout has not yet expired.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005467 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
5468 mConfig.pointerGestureTapDragInterval);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005469 } else {
5470 // The tap is finished.
5471#if DEBUG_GESTURES
5472 ALOGD("Gestures: TAP finished");
5473#endif
5474 *outFinishPreviousGesture = true;
5475
5476 mPointerGesture.activeGestureId = -1;
5477 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5478 mPointerGesture.currentGestureIdBits.clear();
5479
5480 mPointerVelocityControl.reset();
5481 return true;
5482 }
5483 }
5484
5485 // We did not handle this timeout.
5486 return false;
5487 }
5488
Michael Wright842500e2015-03-13 17:32:02 -07005489 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
5490 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005491
5492 // Update the velocity tracker.
5493 {
5494 VelocityTracker::Position positions[MAX_POINTERS];
5495 uint32_t count = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005496 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005497 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005498 const RawPointerData::Pointer& pointer =
5499 mCurrentRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005500 positions[count].x = pointer.x * mPointerXMovementScale;
5501 positions[count].y = pointer.y * mPointerYMovementScale;
5502 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005503 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
5504 positions);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005505 }
5506
5507 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
5508 // to NEUTRAL, then we should not generate tap event.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005509 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER &&
5510 mPointerGesture.lastGestureMode != PointerGesture::TAP &&
5511 mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005512 mPointerGesture.resetTap();
5513 }
5514
5515 // Pick a new active touch id if needed.
5516 // Choose an arbitrary pointer that just went down, if there is one.
5517 // Otherwise choose an arbitrary remaining pointer.
5518 // This guarantees we always have an active touch id when there is at least one pointer.
5519 // We keep the same active touch id for as long as possible.
Michael Wrightd02c5b62014-02-10 15:10:22 -08005520 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
5521 int32_t activeTouchId = lastActiveTouchId;
5522 if (activeTouchId < 0) {
Michael Wright842500e2015-03-13 17:32:02 -07005523 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005524 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005525 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005526 mPointerGesture.firstTouchTime = when;
5527 }
Michael Wright842500e2015-03-13 17:32:02 -07005528 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wright842500e2015-03-13 17:32:02 -07005529 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005530 activeTouchId = mPointerGesture.activeTouchId =
Michael Wright842500e2015-03-13 17:32:02 -07005531 mCurrentCookedState.fingerIdBits.firstMarkedBit();
Michael Wrightd02c5b62014-02-10 15:10:22 -08005532 } else {
5533 activeTouchId = mPointerGesture.activeTouchId = -1;
5534 }
5535 }
5536
5537 // Determine whether we are in quiet time.
5538 bool isQuietTime = false;
5539 if (activeTouchId < 0) {
5540 mPointerGesture.resetQuietTime();
5541 } else {
5542 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
5543 if (!isQuietTime) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005544 if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS ||
5545 mPointerGesture.lastGestureMode == PointerGesture::SWIPE ||
5546 mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) &&
5547 currentFingerCount < 2) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005548 // Enter quiet time when exiting swipe or freeform state.
5549 // This is to prevent accidentally entering the hover state and flinging the
5550 // pointer when finishing a swipe and there is still one pointer left onscreen.
5551 isQuietTime = true;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005552 } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG &&
5553 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005554 // Enter quiet time when releasing the button and there are still two or more
5555 // fingers down. This may indicate that one finger was used to press the button
5556 // but it has not gone up yet.
5557 isQuietTime = true;
5558 }
5559 if (isQuietTime) {
5560 mPointerGesture.quietTime = when;
5561 }
5562 }
5563 }
5564
5565 // Switch states based on button and pointer state.
5566 if (isQuietTime) {
5567 // Case 1: Quiet time. (QUIET)
5568#if DEBUG_GESTURES
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005569 ALOGD("Gestures: QUIET for next %0.3fms",
5570 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005571#endif
5572 if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) {
5573 *outFinishPreviousGesture = true;
5574 }
5575
5576 mPointerGesture.activeGestureId = -1;
5577 mPointerGesture.currentGestureMode = PointerGesture::QUIET;
5578 mPointerGesture.currentGestureIdBits.clear();
5579
5580 mPointerVelocityControl.reset();
Michael Wright842500e2015-03-13 17:32:02 -07005581 } else if (isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005582 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
5583 // The pointer follows the active touch point.
5584 // Emit DOWN, MOVE, UP events at the pointer location.
5585 //
5586 // Only the active touch matters; other fingers are ignored. This policy helps
5587 // to handle the case where the user places a second finger on the touch pad
5588 // to apply the necessary force to depress an integrated button below the surface.
5589 // We don't want the second finger to be delivered to applications.
5590 //
5591 // For this to work well, we need to make sure to track the pointer that is really
5592 // active. If the user first puts one finger down to click then adds another
5593 // finger to drag then the active pointer should switch to the finger that is
5594 // being dragged.
5595#if DEBUG_GESTURES
5596 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005597 "currentFingerCount=%d",
5598 activeTouchId, currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005599#endif
5600 // Reset state when just starting.
5601 if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) {
5602 *outFinishPreviousGesture = true;
5603 mPointerGesture.activeGestureId = 0;
5604 }
5605
5606 // Switch pointers if needed.
5607 // Find the fastest pointer and follow it.
5608 if (activeTouchId >= 0 && currentFingerCount > 1) {
5609 int32_t bestId = -1;
5610 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005611 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005612 uint32_t id = idBits.clearFirstMarkedBit();
5613 float vx, vy;
5614 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
5615 float speed = hypotf(vx, vy);
5616 if (speed > bestSpeed) {
5617 bestId = id;
5618 bestSpeed = speed;
5619 }
5620 }
5621 }
5622 if (bestId >= 0 && bestId != activeTouchId) {
5623 mPointerGesture.activeTouchId = activeTouchId = bestId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005624#if DEBUG_GESTURES
5625 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005626 "bestId=%d, bestSpeed=%0.3f",
5627 bestId, bestSpeed);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005628#endif
5629 }
5630 }
5631
Jun Mukaifa1706a2015-12-03 01:14:46 -08005632 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005633 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005634 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005635 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005636 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005637 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005638 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5639 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005640
5641 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5642 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5643
5644 // Move the pointer using a relative motion.
5645 // When using spots, the click will occur at the position of the anchor
5646 // spot and all other spots will move there.
5647 mPointerController->move(deltaX, deltaY);
5648 } else {
5649 mPointerVelocityControl.reset();
5650 }
5651
5652 float x, y;
5653 mPointerController->getPosition(&x, &y);
5654
5655 mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG;
5656 mPointerGesture.currentGestureIdBits.clear();
5657 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5658 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5659 mPointerGesture.currentGestureProperties[0].clear();
5660 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
5661 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
5662 mPointerGesture.currentGestureCoords[0].clear();
5663 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5664 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5665 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
5666 } else if (currentFingerCount == 0) {
5667 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
5668 if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) {
5669 *outFinishPreviousGesture = true;
5670 }
5671
5672 // Watch for taps coming out of HOVER or TAP_DRAG mode.
5673 // Checking for taps after TAP_DRAG allows us to detect double-taps.
5674 bool tapped = false;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005675 if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER ||
5676 mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) &&
5677 lastFingerCount == 1) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005678 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
5679 float x, y;
5680 mPointerController->getPosition(&x, &y);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005681 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
5682 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005683#if DEBUG_GESTURES
5684 ALOGD("Gestures: TAP");
5685#endif
5686
5687 mPointerGesture.tapUpTime = when;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005688 getContext()->requestTimeoutAtTime(when +
5689 mConfig.pointerGestureTapDragInterval);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005690
5691 mPointerGesture.activeGestureId = 0;
5692 mPointerGesture.currentGestureMode = PointerGesture::TAP;
5693 mPointerGesture.currentGestureIdBits.clear();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005694 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5695 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005696 mPointerGesture.currentGestureProperties[0].clear();
5697 mPointerGesture.currentGestureProperties[0].id =
5698 mPointerGesture.activeGestureId;
5699 mPointerGesture.currentGestureProperties[0].toolType =
5700 AMOTION_EVENT_TOOL_TYPE_FINGER;
5701 mPointerGesture.currentGestureCoords[0].clear();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005702 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
5703 mPointerGesture.tapX);
5704 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
5705 mPointerGesture.tapY);
5706 mPointerGesture.currentGestureCoords[0]
5707 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005708
5709 tapped = true;
5710 } else {
5711#if DEBUG_GESTURES
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005712 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
5713 y - mPointerGesture.tapY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005714#endif
5715 }
5716 } else {
5717#if DEBUG_GESTURES
5718 if (mPointerGesture.tapDownTime != LLONG_MIN) {
5719 ALOGD("Gestures: Not a TAP, %0.3fms since down",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005720 (when - mPointerGesture.tapDownTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005721 } else {
5722 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
5723 }
5724#endif
5725 }
5726 }
5727
5728 mPointerVelocityControl.reset();
5729
5730 if (!tapped) {
5731#if DEBUG_GESTURES
5732 ALOGD("Gestures: NEUTRAL");
5733#endif
5734 mPointerGesture.activeGestureId = -1;
5735 mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL;
5736 mPointerGesture.currentGestureIdBits.clear();
5737 }
5738 } else if (currentFingerCount == 1) {
5739 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
5740 // The pointer follows the active touch point.
5741 // When in HOVER, emit HOVER_MOVE events at the pointer location.
5742 // When in TAP_DRAG, emit MOVE events at the pointer location.
5743 ALOG_ASSERT(activeTouchId >= 0);
5744
5745 mPointerGesture.currentGestureMode = PointerGesture::HOVER;
5746 if (mPointerGesture.lastGestureMode == PointerGesture::TAP) {
5747 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
5748 float x, y;
5749 mPointerController->getPosition(&x, &y);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005750 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
5751 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005752 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5753 } else {
5754#if DEBUG_GESTURES
5755 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005756 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005757#endif
5758 }
5759 } else {
5760#if DEBUG_GESTURES
5761 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005762 (when - mPointerGesture.tapUpTime) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005763#endif
5764 }
5765 } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) {
5766 mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG;
5767 }
5768
Jun Mukaifa1706a2015-12-03 01:14:46 -08005769 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07005770 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005771 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005772 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005773 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07005774 mLastRawState.rawPointerData.pointerForId(activeTouchId);
Jun Mukaifa1706a2015-12-03 01:14:46 -08005775 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
5776 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005777
5778 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
5779 mPointerVelocityControl.move(when, &deltaX, &deltaY);
5780
5781 // Move the pointer using a relative motion.
5782 // When using spots, the hover or drag will occur at the position of the anchor spot.
5783 mPointerController->move(deltaX, deltaY);
5784 } else {
5785 mPointerVelocityControl.reset();
5786 }
5787
5788 bool down;
5789 if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) {
5790#if DEBUG_GESTURES
5791 ALOGD("Gestures: TAP_DRAG");
5792#endif
5793 down = true;
5794 } else {
5795#if DEBUG_GESTURES
5796 ALOGD("Gestures: HOVER");
5797#endif
5798 if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) {
5799 *outFinishPreviousGesture = true;
5800 }
5801 mPointerGesture.activeGestureId = 0;
5802 down = false;
5803 }
5804
5805 float x, y;
5806 mPointerController->getPosition(&x, &y);
5807
5808 mPointerGesture.currentGestureIdBits.clear();
5809 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
5810 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
5811 mPointerGesture.currentGestureProperties[0].clear();
5812 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005813 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005814 mPointerGesture.currentGestureCoords[0].clear();
5815 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
5816 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
5817 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005818 down ? 1.0f : 0.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005819
5820 if (lastFingerCount == 0 && currentFingerCount != 0) {
5821 mPointerGesture.resetTap();
5822 mPointerGesture.tapDownTime = when;
5823 mPointerGesture.tapX = x;
5824 mPointerGesture.tapY = y;
5825 }
5826 } else {
5827 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
5828 // We need to provide feedback for each finger that goes down so we cannot wait
5829 // for the fingers to move before deciding what to do.
5830 //
5831 // The ambiguous case is deciding what to do when there are two fingers down but they
5832 // have not moved enough to determine whether they are part of a drag or part of a
5833 // freeform gesture, or just a press or long-press at the pointer location.
5834 //
5835 // When there are two fingers we start with the PRESS hypothesis and we generate a
5836 // down at the pointer location.
5837 //
5838 // When the two fingers move enough or when additional fingers are added, we make
5839 // a decision to transition into SWIPE or FREEFORM mode accordingly.
5840 ALOG_ASSERT(activeTouchId >= 0);
5841
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005842 bool settled = when >=
5843 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
5844 if (mPointerGesture.lastGestureMode != PointerGesture::PRESS &&
5845 mPointerGesture.lastGestureMode != PointerGesture::SWIPE &&
5846 mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005847 *outFinishPreviousGesture = true;
5848 } else if (!settled && currentFingerCount > lastFingerCount) {
5849 // Additional pointers have gone down but not yet settled.
5850 // Reset the gesture.
5851#if DEBUG_GESTURES
5852 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005853 "settle time remaining %0.3fms",
5854 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
5855 when) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005856#endif
5857 *outCancelPreviousGesture = true;
5858 } else {
5859 // Continue previous gesture.
5860 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
5861 }
5862
5863 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
5864 mPointerGesture.currentGestureMode = PointerGesture::PRESS;
5865 mPointerGesture.activeGestureId = 0;
5866 mPointerGesture.referenceIdBits.clear();
5867 mPointerVelocityControl.reset();
5868
5869 // Use the centroid and pointer location as the reference points for the gesture.
5870#if DEBUG_GESTURES
5871 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005872 "settle time remaining %0.3fms",
5873 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
5874 when) * 0.000001f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005875#endif
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005876 mCurrentRawState.rawPointerData
5877 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
5878 &mPointerGesture.referenceTouchY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005879 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005880 &mPointerGesture.referenceGestureY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005881 }
5882
5883 // Clear the reference deltas for fingers not yet included in the reference calculation.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005884 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
5885 ~mPointerGesture.referenceIdBits.value);
5886 !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005887 uint32_t id = idBits.clearFirstMarkedBit();
5888 mPointerGesture.referenceDeltas[id].dx = 0;
5889 mPointerGesture.referenceDeltas[id].dy = 0;
5890 }
Michael Wright842500e2015-03-13 17:32:02 -07005891 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
Michael Wrightd02c5b62014-02-10 15:10:22 -08005892
5893 // Add delta for all fingers and calculate a common movement delta.
5894 float commonDeltaX = 0, commonDeltaY = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005895 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
5896 mCurrentCookedState.fingerIdBits.value);
5897 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005898 bool first = (idBits == commonIdBits);
5899 uint32_t id = idBits.clearFirstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005900 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
5901 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005902 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
5903 delta.dx += cpd.x - lpd.x;
5904 delta.dy += cpd.y - lpd.y;
5905
5906 if (first) {
5907 commonDeltaX = delta.dx;
5908 commonDeltaY = delta.dy;
5909 } else {
5910 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
5911 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
5912 }
5913 }
5914
5915 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
5916 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) {
5917 float dist[MAX_POINTER_ID + 1];
5918 int32_t distOverThreshold = 0;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005919 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005920 uint32_t id = idBits.clearFirstMarkedBit();
5921 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005922 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005923 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
5924 distOverThreshold += 1;
5925 }
5926 }
5927
5928 // Only transition when at least two pointers have moved further than
5929 // the minimum distance threshold.
5930 if (distOverThreshold >= 2) {
5931 if (currentFingerCount > 2) {
5932 // There are more than two pointers, switch to FREEFORM.
5933#if DEBUG_GESTURES
5934 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005935 currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005936#endif
5937 *outCancelPreviousGesture = true;
5938 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5939 } else {
5940 // There are exactly two pointers.
Michael Wright842500e2015-03-13 17:32:02 -07005941 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005942 uint32_t id1 = idBits.clearFirstMarkedBit();
5943 uint32_t id2 = idBits.firstMarkedBit();
Michael Wright842500e2015-03-13 17:32:02 -07005944 const RawPointerData::Pointer& p1 =
5945 mCurrentRawState.rawPointerData.pointerForId(id1);
5946 const RawPointerData::Pointer& p2 =
5947 mCurrentRawState.rawPointerData.pointerForId(id2);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005948 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
5949 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
5950 // There are two pointers but they are too far apart for a SWIPE,
5951 // switch to FREEFORM.
5952#if DEBUG_GESTURES
5953 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005954 mutualDistance, mPointerGestureMaxSwipeWidth);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005955#endif
5956 *outCancelPreviousGesture = true;
5957 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
5958 } else {
5959 // There are two pointers. Wait for both pointers to start moving
5960 // before deciding whether this is a SWIPE or FREEFORM gesture.
5961 float dist1 = dist[id1];
5962 float dist2 = dist[id2];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005963 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
5964 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08005965 // Calculate the dot product of the displacement vectors.
5966 // When the vectors are oriented in approximately the same direction,
5967 // the angle betweeen them is near zero and the cosine of the angle
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005968 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
5969 // mag(v2).
Michael Wrightd02c5b62014-02-10 15:10:22 -08005970 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
5971 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
5972 float dx1 = delta1.dx * mPointerXZoomScale;
5973 float dy1 = delta1.dy * mPointerYZoomScale;
5974 float dx2 = delta2.dx * mPointerXZoomScale;
5975 float dy2 = delta2.dy * mPointerYZoomScale;
5976 float dot = dx1 * dx2 + dy1 * dy2;
5977 float cosine = dot / (dist1 * dist2); // denominator always > 0
5978 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
5979 // Pointers are moving in the same direction. Switch to SWIPE.
5980#if DEBUG_GESTURES
5981 ALOGD("Gestures: PRESS transitioned to SWIPE, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005982 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5983 "cosine %0.3f >= %0.3f",
5984 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
5985 mConfig.pointerGestureMultitouchMinDistance, cosine,
5986 mConfig.pointerGestureSwipeTransitionAngleCosine);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005987#endif
5988 mPointerGesture.currentGestureMode = PointerGesture::SWIPE;
5989 } else {
5990 // Pointers are moving in different directions. Switch to FREEFORM.
5991#if DEBUG_GESTURES
5992 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07005993 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
5994 "cosine %0.3f < %0.3f",
5995 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
5996 mConfig.pointerGestureMultitouchMinDistance, cosine,
5997 mConfig.pointerGestureSwipeTransitionAngleCosine);
Michael Wrightd02c5b62014-02-10 15:10:22 -08005998#endif
5999 *outCancelPreviousGesture = true;
6000 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6001 }
6002 }
6003 }
6004 }
6005 }
6006 } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
6007 // Switch from SWIPE to FREEFORM if additional pointers go down.
6008 // Cancel previous gesture.
6009 if (currentFingerCount > 2) {
6010#if DEBUG_GESTURES
6011 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006012 currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006013#endif
6014 *outCancelPreviousGesture = true;
6015 mPointerGesture.currentGestureMode = PointerGesture::FREEFORM;
6016 }
6017 }
6018
6019 // Move the reference points based on the overall group motion of the fingers
6020 // except in PRESS mode while waiting for a transition to occur.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006021 if (mPointerGesture.currentGestureMode != PointerGesture::PRESS &&
6022 (commonDeltaX || commonDeltaY)) {
6023 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006024 uint32_t id = idBits.clearFirstMarkedBit();
6025 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
6026 delta.dx = 0;
6027 delta.dy = 0;
6028 }
6029
6030 mPointerGesture.referenceTouchX += commonDeltaX;
6031 mPointerGesture.referenceTouchY += commonDeltaY;
6032
6033 commonDeltaX *= mPointerXMovementScale;
6034 commonDeltaY *= mPointerYMovementScale;
6035
6036 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
6037 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
6038
6039 mPointerGesture.referenceGestureX += commonDeltaX;
6040 mPointerGesture.referenceGestureY += commonDeltaY;
6041 }
6042
6043 // Report gestures.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006044 if (mPointerGesture.currentGestureMode == PointerGesture::PRESS ||
6045 mPointerGesture.currentGestureMode == PointerGesture::SWIPE) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006046 // PRESS or SWIPE mode.
6047#if DEBUG_GESTURES
6048 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006049 "activeGestureId=%d, currentTouchPointerCount=%d",
6050 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006051#endif
6052 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6053
6054 mPointerGesture.currentGestureIdBits.clear();
6055 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
6056 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
6057 mPointerGesture.currentGestureProperties[0].clear();
6058 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006059 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006060 mPointerGesture.currentGestureCoords[0].clear();
6061 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006062 mPointerGesture.referenceGestureX);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006063 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006064 mPointerGesture.referenceGestureY);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006065 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
6066 } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) {
6067 // FREEFORM mode.
6068#if DEBUG_GESTURES
6069 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006070 "activeGestureId=%d, currentTouchPointerCount=%d",
6071 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006072#endif
6073 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
6074
6075 mPointerGesture.currentGestureIdBits.clear();
6076
6077 BitSet32 mappedTouchIdBits;
6078 BitSet32 usedGestureIdBits;
6079 if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) {
6080 // Initially, assign the active gesture id to the active touch point
6081 // if there is one. No other touch id bits are mapped yet.
6082 if (!*outCancelPreviousGesture) {
6083 mappedTouchIdBits.markBit(activeTouchId);
6084 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
6085 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
6086 mPointerGesture.activeGestureId;
6087 } else {
6088 mPointerGesture.activeGestureId = -1;
6089 }
6090 } else {
6091 // Otherwise, assume we mapped all touches from the previous frame.
6092 // Reuse all mappings that are still applicable.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006093 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
6094 mCurrentCookedState.fingerIdBits.value;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006095 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
6096
6097 // Check whether we need to choose a new active gesture id because the
6098 // current went went up.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006099 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
6100 ~mCurrentCookedState.fingerIdBits.value);
6101 !upTouchIdBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006102 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
6103 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
6104 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
6105 mPointerGesture.activeGestureId = -1;
6106 break;
6107 }
6108 }
6109 }
6110
6111#if DEBUG_GESTURES
6112 ALOGD("Gestures: FREEFORM follow up "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006113 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
6114 "activeGestureId=%d",
6115 mappedTouchIdBits.value, usedGestureIdBits.value,
6116 mPointerGesture.activeGestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006117#endif
6118
Michael Wright842500e2015-03-13 17:32:02 -07006119 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006120 for (uint32_t i = 0; i < currentFingerCount; i++) {
6121 uint32_t touchId = idBits.clearFirstMarkedBit();
6122 uint32_t gestureId;
6123 if (!mappedTouchIdBits.hasBit(touchId)) {
6124 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
6125 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
6126#if DEBUG_GESTURES
6127 ALOGD("Gestures: FREEFORM "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006128 "new mapping for touch id %d -> gesture id %d",
6129 touchId, gestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006130#endif
6131 } else {
6132 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
6133#if DEBUG_GESTURES
6134 ALOGD("Gestures: FREEFORM "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006135 "existing mapping for touch id %d -> gesture id %d",
6136 touchId, gestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006137#endif
6138 }
6139 mPointerGesture.currentGestureIdBits.markBit(gestureId);
6140 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
6141
6142 const RawPointerData::Pointer& pointer =
Michael Wright842500e2015-03-13 17:32:02 -07006143 mCurrentRawState.rawPointerData.pointerForId(touchId);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006144 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
6145 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006146 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6147
6148 mPointerGesture.currentGestureProperties[i].clear();
6149 mPointerGesture.currentGestureProperties[i].id = gestureId;
6150 mPointerGesture.currentGestureProperties[i].toolType =
6151 AMOTION_EVENT_TOOL_TYPE_FINGER;
6152 mPointerGesture.currentGestureCoords[i].clear();
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006153 mPointerGesture.currentGestureCoords[i]
6154 .setAxisValue(AMOTION_EVENT_AXIS_X,
6155 mPointerGesture.referenceGestureX + deltaX);
6156 mPointerGesture.currentGestureCoords[i]
6157 .setAxisValue(AMOTION_EVENT_AXIS_Y,
6158 mPointerGesture.referenceGestureY + deltaY);
6159 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
6160 1.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006161 }
6162
6163 if (mPointerGesture.activeGestureId < 0) {
6164 mPointerGesture.activeGestureId =
6165 mPointerGesture.currentGestureIdBits.firstMarkedBit();
6166#if DEBUG_GESTURES
6167 ALOGD("Gestures: FREEFORM new "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006168 "activeGestureId=%d",
6169 mPointerGesture.activeGestureId);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006170#endif
6171 }
6172 }
6173 }
6174
Michael Wright842500e2015-03-13 17:32:02 -07006175 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006176
6177#if DEBUG_GESTURES
6178 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006179 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
6180 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
6181 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
6182 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
6183 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
6184 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006185 uint32_t id = idBits.clearFirstMarkedBit();
6186 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
6187 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
6188 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
6189 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006190 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6191 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6192 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6193 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006194 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006195 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006196 uint32_t id = idBits.clearFirstMarkedBit();
6197 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
6198 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
6199 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
6200 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006201 "x=%0.3f, y=%0.3f, pressure=%0.3f",
6202 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
6203 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
6204 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006205 }
6206#endif
6207 return true;
6208}
6209
6210void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
6211 mPointerSimple.currentCoords.clear();
6212 mPointerSimple.currentProperties.clear();
6213
6214 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006215 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
6216 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
6217 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
6218 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
6219 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006220 mPointerController->setPosition(x, y);
6221
Michael Wright842500e2015-03-13 17:32:02 -07006222 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006223 down = !hovering;
6224
6225 mPointerController->getPosition(&x, &y);
Michael Wright842500e2015-03-13 17:32:02 -07006226 mPointerSimple.currentCoords.copyFrom(
6227 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006228 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6229 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6230 mPointerSimple.currentProperties.id = 0;
6231 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006232 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006233 } else {
6234 down = false;
6235 hovering = false;
6236 }
6237
6238 dispatchPointerSimple(when, policyFlags, down, hovering);
6239}
6240
6241void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
6242 abortPointerSimple(when, policyFlags);
6243}
6244
6245void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
6246 mPointerSimple.currentCoords.clear();
6247 mPointerSimple.currentProperties.clear();
6248
6249 bool down, hovering;
Michael Wright842500e2015-03-13 17:32:02 -07006250 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
6251 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
6252 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Jun Mukaifa1706a2015-12-03 01:14:46 -08006253 float deltaX = 0, deltaY = 0;
Michael Wright842500e2015-03-13 17:32:02 -07006254 if (mLastCookedState.mouseIdBits.hasBit(id)) {
6255 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006256 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
6257 mLastRawState.rawPointerData.pointers[lastIndex].x) *
6258 mPointerXMovementScale;
6259 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
6260 mLastRawState.rawPointerData.pointers[lastIndex].y) *
6261 mPointerYMovementScale;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006262
6263 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
6264 mPointerVelocityControl.move(when, &deltaX, &deltaY);
6265
6266 mPointerController->move(deltaX, deltaY);
6267 } else {
6268 mPointerVelocityControl.reset();
6269 }
6270
Michael Wright842500e2015-03-13 17:32:02 -07006271 down = isPointerDown(mCurrentRawState.buttonState);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006272 hovering = !down;
6273
6274 float x, y;
6275 mPointerController->getPosition(&x, &y);
6276 mPointerSimple.currentCoords.copyFrom(
Michael Wright842500e2015-03-13 17:32:02 -07006277 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006278 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
6279 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
6280 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006281 hovering ? 0.0f : 1.0f);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006282 mPointerSimple.currentProperties.id = 0;
6283 mPointerSimple.currentProperties.toolType =
Michael Wright842500e2015-03-13 17:32:02 -07006284 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006285 } else {
6286 mPointerVelocityControl.reset();
6287
6288 down = false;
6289 hovering = false;
6290 }
6291
6292 dispatchPointerSimple(when, policyFlags, down, hovering);
6293}
6294
6295void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
6296 abortPointerSimple(when, policyFlags);
6297
6298 mPointerVelocityControl.reset();
6299}
6300
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006301void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
6302 bool hovering) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006303 int32_t metaState = getContext()->getGlobalMetaState();
Arthur Hungc7ad2d02018-12-18 17:41:29 +08006304 int32_t displayId = mViewport.displayId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006305
Garfield Tan00f511d2019-06-12 16:55:40 -07006306 if (down || hovering) {
6307 mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER);
6308 mPointerController->clearSpots();
6309 mPointerController->setButtonState(mCurrentRawState.buttonState);
6310 mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE);
6311 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
6312 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006313 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006314 displayId = mPointerController->getDisplayId();
6315
6316 float xCursorPosition;
6317 float yCursorPosition;
6318 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006319
6320 if (mPointerSimple.down && !down) {
6321 mPointerSimple.down = false;
6322
6323 // Send up.
Garfield Tan00f511d2019-06-12 16:55:40 -07006324 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6325 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
6326 mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006327 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6328 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6329 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6330 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006331 getListener()->notifyMotion(&args);
6332 }
6333
6334 if (mPointerSimple.hovering && !hovering) {
6335 mPointerSimple.hovering = false;
6336
6337 // Send hover exit.
Garfield Tan00f511d2019-06-12 16:55:40 -07006338 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6339 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
6340 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006341 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
6342 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
6343 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6344 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006345 getListener()->notifyMotion(&args);
6346 }
6347
6348 if (down) {
6349 if (!mPointerSimple.down) {
6350 mPointerSimple.down = true;
6351 mPointerSimple.downTime = when;
6352
6353 // Send down.
Garfield Tan00f511d2019-06-12 16:55:40 -07006354 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6355 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
6356 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006357 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6358 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6359 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6360 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006361 getListener()->notifyMotion(&args);
6362 }
6363
6364 // Send move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006365 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6366 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
6367 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006368 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6369 &mPointerSimple.currentCoords, mOrientedXPrecision,
6370 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6371 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006372 getListener()->notifyMotion(&args);
6373 }
6374
6375 if (hovering) {
6376 if (!mPointerSimple.hovering) {
6377 mPointerSimple.hovering = true;
6378
6379 // Send hover enter.
Garfield Tan00f511d2019-06-12 16:55:40 -07006380 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6381 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
6382 metaState, mCurrentRawState.buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006383 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
6384 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
6385 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
6386 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006387 getListener()->notifyMotion(&args);
6388 }
6389
6390 // Send hover move.
Garfield Tan00f511d2019-06-12 16:55:40 -07006391 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6392 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
6393 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006394 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6395 &mPointerSimple.currentCoords, mOrientedXPrecision,
6396 mOrientedYPrecision, xCursorPosition, yCursorPosition,
6397 mPointerSimple.downTime, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006398 getListener()->notifyMotion(&args);
6399 }
6400
Michael Wright842500e2015-03-13 17:32:02 -07006401 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
6402 float vscroll = mCurrentRawState.rawVScroll;
6403 float hscroll = mCurrentRawState.rawHScroll;
Yi Kong9b14ac62018-07-17 13:48:38 -07006404 mWheelYVelocityControl.move(when, nullptr, &vscroll);
6405 mWheelXVelocityControl.move(when, &hscroll, nullptr);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006406
6407 // Send scroll.
6408 PointerCoords pointerCoords;
6409 pointerCoords.copyFrom(mPointerSimple.currentCoords);
6410 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
6411 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
6412
Garfield Tan00f511d2019-06-12 16:55:40 -07006413 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
6414 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
6415 mCurrentRawState.buttonState, MotionClassification::NONE,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006416 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
6417 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
6418 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
6419 /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08006420 getListener()->notifyMotion(&args);
6421 }
6422
6423 // Save state.
6424 if (down || hovering) {
6425 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
6426 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
6427 } else {
6428 mPointerSimple.reset();
6429 }
6430}
6431
6432void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
6433 mPointerSimple.currentCoords.clear();
6434 mPointerSimple.currentProperties.clear();
6435
6436 dispatchPointerSimple(when, policyFlags, false, false);
6437}
6438
6439void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006440 int32_t action, int32_t actionButton, int32_t flags,
6441 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
6442 const PointerProperties* properties,
6443 const PointerCoords* coords, const uint32_t* idToIndex,
6444 BitSet32 idBits, int32_t changedId, float xPrecision,
6445 float yPrecision, nsecs_t downTime) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006446 PointerCoords pointerCoords[MAX_POINTERS];
6447 PointerProperties pointerProperties[MAX_POINTERS];
6448 uint32_t pointerCount = 0;
6449 while (!idBits.isEmpty()) {
6450 uint32_t id = idBits.clearFirstMarkedBit();
6451 uint32_t index = idToIndex[id];
6452 pointerProperties[pointerCount].copyFrom(properties[index]);
6453 pointerCoords[pointerCount].copyFrom(coords[index]);
6454
6455 if (changedId >= 0 && id == uint32_t(changedId)) {
6456 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
6457 }
6458
6459 pointerCount += 1;
6460 }
6461
6462 ALOG_ASSERT(pointerCount != 0);
6463
6464 if (changedId >= 0 && pointerCount == 1) {
6465 // Replace initial down and final up action.
6466 // We can compare the action without masking off the changed pointer index
6467 // because we know the index is 0.
6468 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
6469 action = AMOTION_EVENT_ACTION_DOWN;
6470 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
6471 action = AMOTION_EVENT_ACTION_UP;
6472 } else {
6473 // Can't happen.
6474 ALOG_ASSERT(false);
6475 }
6476 }
Garfield Tan00f511d2019-06-12 16:55:40 -07006477 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6478 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
6479 if (mDeviceMode == DEVICE_MODE_POINTER) {
6480 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
6481 }
Arthur Hung2c9a3342019-07-23 14:18:59 +08006482 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
Siarhei Vishniakouadd89292018-12-13 19:23:36 -08006483 const int32_t deviceId = getDeviceId();
6484 std::vector<TouchVideoFrame> frames = mDevice->getEventHub()->getVideoFrames(deviceId);
Siarhei Vishniakou8154bbd2019-02-15 17:21:03 -06006485 std::for_each(frames.begin(), frames.end(),
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006486 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tan00f511d2019-06-12 16:55:40 -07006487 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, deviceId, source, displayId,
6488 policyFlags, action, actionButton, flags, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07006489 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
6490 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
6491 downTime, std::move(frames));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006492 getListener()->notifyMotion(&args);
6493}
6494
6495bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006496 const PointerCoords* inCoords,
6497 const uint32_t* inIdToIndex,
6498 PointerProperties* outProperties,
6499 PointerCoords* outCoords, const uint32_t* outIdToIndex,
6500 BitSet32 idBits) const {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006501 bool changed = false;
6502 while (!idBits.isEmpty()) {
6503 uint32_t id = idBits.clearFirstMarkedBit();
6504 uint32_t inIndex = inIdToIndex[id];
6505 uint32_t outIndex = outIdToIndex[id];
6506
6507 const PointerProperties& curInProperties = inProperties[inIndex];
6508 const PointerCoords& curInCoords = inCoords[inIndex];
6509 PointerProperties& curOutProperties = outProperties[outIndex];
6510 PointerCoords& curOutCoords = outCoords[outIndex];
6511
6512 if (curInProperties != curOutProperties) {
6513 curOutProperties.copyFrom(curInProperties);
6514 changed = true;
6515 }
6516
6517 if (curInCoords != curOutCoords) {
6518 curOutCoords.copyFrom(curInCoords);
6519 changed = true;
6520 }
6521 }
6522 return changed;
6523}
6524
6525void TouchInputMapper::fadePointer() {
Yi Kong9b14ac62018-07-17 13:48:38 -07006526 if (mPointerController != nullptr) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006527 mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL);
6528 }
6529}
6530
Jeff Brownc9aa6282015-02-11 19:03:28 -08006531void TouchInputMapper::cancelTouch(nsecs_t when) {
6532 abortPointerUsage(when, 0 /*policyFlags*/);
Michael Wright8e812822015-06-22 16:18:21 +01006533 abortTouches(when, 0 /* policyFlags*/);
Jeff Brownc9aa6282015-02-11 19:03:28 -08006534}
6535
Michael Wrightd02c5b62014-02-10 15:10:22 -08006536bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Michael Wright358bcc72018-08-21 04:01:07 +01006537 const float scaledX = x * mXScale;
Michael Wrightc597d612018-08-22 13:49:32 +01006538 const float scaledY = y * mYScale;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006539 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
6540 scaledX >= mPhysicalLeft && scaledX <= mPhysicalLeft + mPhysicalWidth &&
6541 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
6542 scaledY >= mPhysicalTop && scaledY <= mPhysicalTop + mPhysicalHeight;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006543}
6544
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006545const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006546 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006547#if DEBUG_VIRTUAL_KEYS
6548 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006549 "left=%d, top=%d, right=%d, bottom=%d",
6550 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
6551 virtualKey.hitRight, virtualKey.hitBottom);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006552#endif
6553
6554 if (virtualKey.isHit(x, y)) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006555 return &virtualKey;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006556 }
6557 }
6558
Yi Kong9b14ac62018-07-17 13:48:38 -07006559 return nullptr;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006560}
6561
Michael Wright842500e2015-03-13 17:32:02 -07006562void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
6563 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
6564 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006565
Michael Wright842500e2015-03-13 17:32:02 -07006566 current->rawPointerData.clearIdBits();
Michael Wrightd02c5b62014-02-10 15:10:22 -08006567
6568 if (currentPointerCount == 0) {
6569 // No pointers to assign.
6570 return;
6571 }
6572
6573 if (lastPointerCount == 0) {
6574 // All pointers are new.
6575 for (uint32_t i = 0; i < currentPointerCount; i++) {
6576 uint32_t id = i;
Michael Wright842500e2015-03-13 17:32:02 -07006577 current->rawPointerData.pointers[i].id = id;
6578 current->rawPointerData.idToIndex[id] = i;
6579 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006580 }
6581 return;
6582 }
6583
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006584 if (currentPointerCount == 1 && lastPointerCount == 1 &&
6585 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006586 // Only one pointer and no change in count so it must have the same id as before.
Michael Wright842500e2015-03-13 17:32:02 -07006587 uint32_t id = last->rawPointerData.pointers[0].id;
6588 current->rawPointerData.pointers[0].id = id;
6589 current->rawPointerData.idToIndex[id] = 0;
6590 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006591 return;
6592 }
6593
6594 // General case.
6595 // We build a heap of squared euclidean distances between current and last pointers
6596 // associated with the current and last pointer indices. Then, we find the best
6597 // match (by distance) for each current pointer.
6598 // The pointers must have the same tool type but it is possible for them to
6599 // transition from hovering to touching or vice-versa while retaining the same id.
6600 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
6601
6602 uint32_t heapSize = 0;
6603 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006604 currentPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006605 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006606 lastPointerIndex++) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006607 const RawPointerData::Pointer& currentPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006608 current->rawPointerData.pointers[currentPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006609 const RawPointerData::Pointer& lastPointer =
Michael Wright842500e2015-03-13 17:32:02 -07006610 last->rawPointerData.pointers[lastPointerIndex];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006611 if (currentPointer.toolType == lastPointer.toolType) {
6612 int64_t deltaX = currentPointer.x - lastPointer.x;
6613 int64_t deltaY = currentPointer.y - lastPointer.y;
6614
6615 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
6616
6617 // Insert new element into the heap (sift up).
6618 heap[heapSize].currentPointerIndex = currentPointerIndex;
6619 heap[heapSize].lastPointerIndex = lastPointerIndex;
6620 heap[heapSize].distance = distance;
6621 heapSize += 1;
6622 }
6623 }
6624 }
6625
6626 // Heapify
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006627 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006628 startIndex -= 1;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006629 for (uint32_t parentIndex = startIndex;;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006630 uint32_t childIndex = parentIndex * 2 + 1;
6631 if (childIndex >= heapSize) {
6632 break;
6633 }
6634
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006635 if (childIndex + 1 < heapSize &&
6636 heap[childIndex + 1].distance < heap[childIndex].distance) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006637 childIndex += 1;
6638 }
6639
6640 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6641 break;
6642 }
6643
6644 swap(heap[parentIndex], heap[childIndex]);
6645 parentIndex = childIndex;
6646 }
6647 }
6648
6649#if DEBUG_POINTER_ASSIGNMENT
6650 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
6651 for (size_t i = 0; i < heapSize; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006652 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
6653 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006654 }
6655#endif
6656
6657 // Pull matches out by increasing order of distance.
6658 // To avoid reassigning pointers that have already been matched, the loop keeps track
6659 // of which last and current pointers have been matched using the matchedXXXBits variables.
6660 // It also tracks the used pointer id bits.
6661 BitSet32 matchedLastBits(0);
6662 BitSet32 matchedCurrentBits(0);
6663 BitSet32 usedIdBits(0);
6664 bool first = true;
6665 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
6666 while (heapSize > 0) {
6667 if (first) {
6668 // The first time through the loop, we just consume the root element of
6669 // the heap (the one with smallest distance).
6670 first = false;
6671 } else {
6672 // Previous iterations consumed the root element of the heap.
6673 // Pop root element off of the heap (sift down).
6674 heap[0] = heap[heapSize];
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006675 for (uint32_t parentIndex = 0;;) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006676 uint32_t childIndex = parentIndex * 2 + 1;
6677 if (childIndex >= heapSize) {
6678 break;
6679 }
6680
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006681 if (childIndex + 1 < heapSize &&
6682 heap[childIndex + 1].distance < heap[childIndex].distance) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006683 childIndex += 1;
6684 }
6685
6686 if (heap[parentIndex].distance <= heap[childIndex].distance) {
6687 break;
6688 }
6689
6690 swap(heap[parentIndex], heap[childIndex]);
6691 parentIndex = childIndex;
6692 }
6693
6694#if DEBUG_POINTER_ASSIGNMENT
6695 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
6696 for (size_t i = 0; i < heapSize; i++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006697 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
6698 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006699 }
6700#endif
6701 }
6702
6703 heapSize -= 1;
6704
6705 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
6706 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
6707
6708 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
6709 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
6710
6711 matchedCurrentBits.markBit(currentPointerIndex);
6712 matchedLastBits.markBit(lastPointerIndex);
6713
Michael Wright842500e2015-03-13 17:32:02 -07006714 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
6715 current->rawPointerData.pointers[currentPointerIndex].id = id;
6716 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6717 current->rawPointerData.markIdBit(id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006718 current->rawPointerData.isHovering(
6719 currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006720 usedIdBits.markBit(id);
6721
6722#if DEBUG_POINTER_ASSIGNMENT
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006723 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
6724 ", distance=%" PRIu64,
6725 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006726#endif
6727 break;
6728 }
6729 }
6730
6731 // Assign fresh ids to pointers that were not matched in the process.
6732 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
6733 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
6734 uint32_t id = usedIdBits.markFirstUnmarkedBit();
6735
Michael Wright842500e2015-03-13 17:32:02 -07006736 current->rawPointerData.pointers[currentPointerIndex].id = id;
6737 current->rawPointerData.idToIndex[id] = currentPointerIndex;
6738 current->rawPointerData.markIdBit(id,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006739 current->rawPointerData.isHovering(currentPointerIndex));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006740
6741#if DEBUG_POINTER_ASSIGNMENT
Siarhei Vishniakou73215292017-10-13 11:02:44 -07006742 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006743#endif
6744 }
6745}
6746
6747int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
6748 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
6749 return AKEY_STATE_VIRTUAL;
6750 }
6751
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006752 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006753 if (virtualKey.keyCode == keyCode) {
6754 return AKEY_STATE_UP;
6755 }
6756 }
6757
6758 return AKEY_STATE_UNKNOWN;
6759}
6760
6761int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
6762 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
6763 return AKEY_STATE_VIRTUAL;
6764 }
6765
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006766 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006767 if (virtualKey.scanCode == scanCode) {
6768 return AKEY_STATE_UP;
6769 }
6770 }
6771
6772 return AKEY_STATE_UNKNOWN;
6773}
6774
6775bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006776 const int32_t* keyCodes, uint8_t* outFlags) {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08006777 for (const VirtualKey& virtualKey : mVirtualKeys) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006778 for (size_t i = 0; i < numCodes; i++) {
6779 if (virtualKey.keyCode == keyCodes[i]) {
6780 outFlags[i] = 1;
6781 }
6782 }
6783 }
6784
6785 return true;
6786}
6787
Arthur Hung2c9a3342019-07-23 14:18:59 +08006788std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
Arthur Hungc23540e2018-11-29 20:42:11 +08006789 if (mParameters.hasAssociatedDisplay) {
6790 if (mDeviceMode == DEVICE_MODE_POINTER) {
6791 return std::make_optional(mPointerController->getDisplayId());
6792 } else {
6793 return std::make_optional(mViewport.displayId);
6794 }
6795 }
6796 return std::nullopt;
6797}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006798
6799// --- SingleTouchInputMapper ---
6800
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006801SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : TouchInputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006802
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006803SingleTouchInputMapper::~SingleTouchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006804
6805void SingleTouchInputMapper::reset(nsecs_t when) {
6806 mSingleTouchMotionAccumulator.reset(getDevice());
6807
6808 TouchInputMapper::reset(when);
6809}
6810
6811void SingleTouchInputMapper::process(const RawEvent* rawEvent) {
6812 TouchInputMapper::process(rawEvent);
6813
6814 mSingleTouchMotionAccumulator.process(rawEvent);
6815}
6816
Michael Wright842500e2015-03-13 17:32:02 -07006817void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006818 if (mTouchButtonAccumulator.isToolActive()) {
Michael Wright842500e2015-03-13 17:32:02 -07006819 outState->rawPointerData.pointerCount = 1;
6820 outState->rawPointerData.idToIndex[0] = 0;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006821
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006822 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE &&
6823 (mTouchButtonAccumulator.isHovering() ||
6824 (mRawPointerAxes.pressure.valid &&
6825 mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0));
Michael Wright842500e2015-03-13 17:32:02 -07006826 outState->rawPointerData.markIdBit(0, isHovering);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006827
Michael Wright842500e2015-03-13 17:32:02 -07006828 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006829 outPointer.id = 0;
6830 outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX();
6831 outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY();
6832 outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
6833 outPointer.touchMajor = 0;
6834 outPointer.touchMinor = 0;
6835 outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6836 outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth();
6837 outPointer.orientation = 0;
6838 outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance();
6839 outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX();
6840 outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY();
6841 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6842 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6843 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6844 }
6845 outPointer.isHovering = isHovering;
6846 }
6847}
6848
6849void SingleTouchInputMapper::configureRawPointerAxes() {
6850 TouchInputMapper::configureRawPointerAxes();
6851
6852 getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x);
6853 getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y);
6854 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure);
6855 getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor);
6856 getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance);
6857 getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX);
6858 getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY);
6859}
6860
6861bool SingleTouchInputMapper::hasStylus() const {
6862 return mTouchButtonAccumulator.hasStylus();
6863}
6864
Michael Wrightd02c5b62014-02-10 15:10:22 -08006865// --- MultiTouchInputMapper ---
6866
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006867MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : TouchInputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006868
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006869MultiTouchInputMapper::~MultiTouchInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08006870
6871void MultiTouchInputMapper::reset(nsecs_t when) {
6872 mMultiTouchMotionAccumulator.reset(getDevice());
6873
6874 mPointerIdBits.clear();
6875
6876 TouchInputMapper::reset(when);
6877}
6878
6879void MultiTouchInputMapper::process(const RawEvent* rawEvent) {
6880 TouchInputMapper::process(rawEvent);
6881
6882 mMultiTouchMotionAccumulator.process(rawEvent);
6883}
6884
Michael Wright842500e2015-03-13 17:32:02 -07006885void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006886 size_t inCount = mMultiTouchMotionAccumulator.getSlotCount();
6887 size_t outCount = 0;
6888 BitSet32 newPointerIdBits;
gaoshang1a632de2016-08-24 10:23:50 +08006889 mHavePointerIds = true;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006890
6891 for (size_t inIndex = 0; inIndex < inCount; inIndex++) {
6892 const MultiTouchMotionAccumulator::Slot* inSlot =
6893 mMultiTouchMotionAccumulator.getSlot(inIndex);
6894 if (!inSlot->isInUse()) {
6895 continue;
6896 }
6897
6898 if (outCount >= MAX_POINTERS) {
6899#if DEBUG_POINTERS
6900 ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006901 "ignoring the rest.",
6902 getDeviceName().c_str(), MAX_POINTERS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006903#endif
6904 break; // too many fingers!
6905 }
6906
Michael Wright842500e2015-03-13 17:32:02 -07006907 RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount];
Michael Wrightd02c5b62014-02-10 15:10:22 -08006908 outPointer.x = inSlot->getX();
6909 outPointer.y = inSlot->getY();
6910 outPointer.pressure = inSlot->getPressure();
6911 outPointer.touchMajor = inSlot->getTouchMajor();
6912 outPointer.touchMinor = inSlot->getTouchMinor();
6913 outPointer.toolMajor = inSlot->getToolMajor();
6914 outPointer.toolMinor = inSlot->getToolMinor();
6915 outPointer.orientation = inSlot->getOrientation();
6916 outPointer.distance = inSlot->getDistance();
6917 outPointer.tiltX = 0;
6918 outPointer.tiltY = 0;
6919
6920 outPointer.toolType = inSlot->getToolType();
6921 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6922 outPointer.toolType = mTouchButtonAccumulator.getToolType();
6923 if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
6924 outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
6925 }
6926 }
6927
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006928 bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE &&
6929 (mTouchButtonAccumulator.isHovering() ||
6930 (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0));
Michael Wrightd02c5b62014-02-10 15:10:22 -08006931 outPointer.isHovering = isHovering;
6932
6933 // Assign pointer id using tracking id if available.
gaoshang1a632de2016-08-24 10:23:50 +08006934 if (mHavePointerIds) {
6935 int32_t trackingId = inSlot->getTrackingId();
6936 int32_t id = -1;
6937 if (trackingId >= 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006938 for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty();) {
gaoshang1a632de2016-08-24 10:23:50 +08006939 uint32_t n = idBits.clearFirstMarkedBit();
6940 if (mPointerTrackingIdMap[n] == trackingId) {
6941 id = n;
6942 }
6943 }
6944
6945 if (id < 0 && !mPointerIdBits.isFull()) {
6946 id = mPointerIdBits.markFirstUnmarkedBit();
6947 mPointerTrackingIdMap[id] = trackingId;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006948 }
Michael Wright842500e2015-03-13 17:32:02 -07006949 }
gaoshang1a632de2016-08-24 10:23:50 +08006950 if (id < 0) {
6951 mHavePointerIds = false;
6952 outState->rawPointerData.clearIdBits();
6953 newPointerIdBits.clear();
6954 } else {
6955 outPointer.id = id;
6956 outState->rawPointerData.idToIndex[id] = outCount;
6957 outState->rawPointerData.markIdBit(id, isHovering);
6958 newPointerIdBits.markBit(id);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006959 }
Michael Wright842500e2015-03-13 17:32:02 -07006960 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08006961 outCount += 1;
6962 }
6963
Michael Wright842500e2015-03-13 17:32:02 -07006964 outState->rawPointerData.pointerCount = outCount;
Michael Wrightd02c5b62014-02-10 15:10:22 -08006965 mPointerIdBits = newPointerIdBits;
6966
6967 mMultiTouchMotionAccumulator.finishSync();
6968}
6969
6970void MultiTouchInputMapper::configureRawPointerAxes() {
6971 TouchInputMapper::configureRawPointerAxes();
6972
6973 getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x);
6974 getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y);
6975 getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor);
6976 getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor);
6977 getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor);
6978 getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor);
6979 getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation);
6980 getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure);
6981 getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance);
6982 getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId);
6983 getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot);
6984
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006985 if (mRawPointerAxes.trackingId.valid && mRawPointerAxes.slot.valid &&
6986 mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08006987 size_t slotCount = mRawPointerAxes.slot.maxValue + 1;
6988 if (slotCount > MAX_SLOTS) {
Narayan Kamath37764c72014-03-27 14:21:09 +00006989 ALOGW("MultiTouch Device %s reported %zu slots but the framework "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006990 "only supports a maximum of %zu slots at this time.",
6991 getDeviceName().c_str(), slotCount, MAX_SLOTS);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006992 slotCount = MAX_SLOTS;
6993 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006994 mMultiTouchMotionAccumulator.configure(getDevice(), slotCount, true /*usingSlotsProtocol*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006995 } else {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07006996 mMultiTouchMotionAccumulator.configure(getDevice(), MAX_POINTERS,
6997 false /*usingSlotsProtocol*/);
Michael Wrightd02c5b62014-02-10 15:10:22 -08006998 }
6999}
7000
7001bool MultiTouchInputMapper::hasStylus() const {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007002 return mMultiTouchMotionAccumulator.hasStylus() || mTouchButtonAccumulator.hasStylus();
Michael Wrightd02c5b62014-02-10 15:10:22 -08007003}
7004
Michael Wright842500e2015-03-13 17:32:02 -07007005// --- ExternalStylusInputMapper
7006
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007007ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) : InputMapper(device) {}
Michael Wright842500e2015-03-13 17:32:02 -07007008
7009uint32_t ExternalStylusInputMapper::getSources() {
7010 return AINPUT_SOURCE_STYLUS;
7011}
7012
7013void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7014 InputMapper::populateDeviceInfo(info);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007015 info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS, 0.0f, 1.0f, 0.0f, 0.0f,
7016 0.0f);
Michael Wright842500e2015-03-13 17:32:02 -07007017}
7018
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007019void ExternalStylusInputMapper::dump(std::string& dump) {
7020 dump += INDENT2 "External Stylus Input Mapper:\n";
7021 dump += INDENT3 "Raw Stylus Axes:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007022 dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure");
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007023 dump += INDENT3 "Stylus State:\n";
Michael Wright842500e2015-03-13 17:32:02 -07007024 dumpStylusState(dump, mStylusState);
7025}
7026
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007027void ExternalStylusInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
7028 uint32_t changes) {
Michael Wright842500e2015-03-13 17:32:02 -07007029 getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis);
7030 mTouchButtonAccumulator.configure(getDevice());
7031}
7032
7033void ExternalStylusInputMapper::reset(nsecs_t when) {
7034 InputDevice* device = getDevice();
7035 mSingleTouchMotionAccumulator.reset(device);
7036 mTouchButtonAccumulator.reset(device);
7037 InputMapper::reset(when);
7038}
7039
7040void ExternalStylusInputMapper::process(const RawEvent* rawEvent) {
7041 mSingleTouchMotionAccumulator.process(rawEvent);
7042 mTouchButtonAccumulator.process(rawEvent);
7043
7044 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
7045 sync(rawEvent->when);
7046 }
7047}
7048
7049void ExternalStylusInputMapper::sync(nsecs_t when) {
7050 mStylusState.clear();
7051
7052 mStylusState.when = when;
7053
Michael Wright45ccacf2015-04-21 19:01:58 +01007054 mStylusState.toolType = mTouchButtonAccumulator.getToolType();
7055 if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
7056 mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
7057 }
7058
Michael Wright842500e2015-03-13 17:32:02 -07007059 int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure();
7060 if (mRawPressureAxis.valid) {
7061 mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue;
7062 } else if (mTouchButtonAccumulator.isToolActive()) {
7063 mStylusState.pressure = 1.0f;
7064 } else {
7065 mStylusState.pressure = 0.0f;
7066 }
7067
7068 mStylusState.buttons = mTouchButtonAccumulator.getButtonState();
Michael Wright842500e2015-03-13 17:32:02 -07007069
7070 mContext->dispatchExternalStylusState(mStylusState);
7071}
7072
Michael Wrightd02c5b62014-02-10 15:10:22 -08007073// --- JoystickInputMapper ---
7074
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007075JoystickInputMapper::JoystickInputMapper(InputDevice* device) : InputMapper(device) {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08007076
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007077JoystickInputMapper::~JoystickInputMapper() {}
Michael Wrightd02c5b62014-02-10 15:10:22 -08007078
7079uint32_t JoystickInputMapper::getSources() {
7080 return AINPUT_SOURCE_JOYSTICK;
7081}
7082
7083void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
7084 InputMapper::populateDeviceInfo(info);
7085
7086 for (size_t i = 0; i < mAxes.size(); i++) {
7087 const Axis& axis = mAxes.valueAt(i);
7088 addMotionRange(axis.axisInfo.axis, axis, info);
7089
7090 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7091 addMotionRange(axis.axisInfo.highAxis, axis, info);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007092 }
7093 }
7094}
7095
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007096void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info) {
7097 info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz,
7098 axis.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007099 /* In order to ease the transition for developers from using the old axes
7100 * to the newer, more semantically correct axes, we'll continue to register
7101 * the old axes as duplicates of their corresponding new ones. */
7102 int32_t compatAxis = getCompatAxis(axisId);
7103 if (compatAxis >= 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007104 info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat,
7105 axis.fuzz, axis.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007106 }
7107}
7108
7109/* A mapping from axes the joystick actually has to the axes that should be
7110 * artificially created for compatibility purposes.
7111 * Returns -1 if no compatibility axis is needed. */
7112int32_t JoystickInputMapper::getCompatAxis(int32_t axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007113 switch (axis) {
7114 case AMOTION_EVENT_AXIS_LTRIGGER:
7115 return AMOTION_EVENT_AXIS_BRAKE;
7116 case AMOTION_EVENT_AXIS_RTRIGGER:
7117 return AMOTION_EVENT_AXIS_GAS;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007118 }
7119 return -1;
7120}
7121
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007122void JoystickInputMapper::dump(std::string& dump) {
7123 dump += INDENT2 "Joystick Input Mapper:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007124
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007125 dump += INDENT3 "Axes:\n";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007126 size_t numAxes = mAxes.size();
7127 for (size_t i = 0; i < numAxes; i++) {
7128 const Axis& axis = mAxes.valueAt(i);
7129 const char* label = getAxisLabel(axis.axisInfo.axis);
7130 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007131 dump += StringPrintf(INDENT4 "%s", label);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007132 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007133 dump += StringPrintf(INDENT4 "%d", axis.axisInfo.axis);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007134 }
7135 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7136 label = getAxisLabel(axis.axisInfo.highAxis);
7137 if (label) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007138 dump += StringPrintf(" / %s (split at %d)", label, axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007139 } else {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007140 dump += StringPrintf(" / %d (split at %d)", axis.axisInfo.highAxis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007141 axis.axisInfo.splitValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007142 }
7143 } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) {
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007144 dump += " (invert)";
Michael Wrightd02c5b62014-02-10 15:10:22 -08007145 }
7146
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007147 dump += StringPrintf(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007148 axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007149 dump += StringPrintf(INDENT4 " scale=%0.5f, offset=%0.5f, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007150 "highScale=%0.5f, highOffset=%0.5f\n",
7151 axis.scale, axis.offset, axis.highScale, axis.highOffset);
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -08007152 dump += StringPrintf(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007153 "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n",
7154 mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue,
7155 axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz,
7156 axis.rawAxisInfo.resolution);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007157 }
7158}
7159
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007160void JoystickInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
7161 uint32_t changes) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007162 InputMapper::configure(when, config, changes);
7163
7164 if (!changes) { // first time only
7165 // Collect all axes.
7166 for (int32_t abs = 0; abs <= ABS_MAX; abs++) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007167 if (!(getAbsAxisUsage(abs, getDevice()->getClasses()) & INPUT_DEVICE_CLASS_JOYSTICK)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007168 continue; // axis must be claimed by a different device
7169 }
7170
7171 RawAbsoluteAxisInfo rawAxisInfo;
7172 getAbsoluteAxisInfo(abs, &rawAxisInfo);
7173 if (rawAxisInfo.valid) {
7174 // Map axis.
7175 AxisInfo axisInfo;
7176 bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo);
7177 if (!explicitlyMapped) {
7178 // Axis is not explicitly mapped, will choose a generic axis later.
7179 axisInfo.mode = AxisInfo::MODE_NORMAL;
7180 axisInfo.axis = -1;
7181 }
7182
7183 // Apply flat override.
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007184 int32_t rawFlat =
7185 axisInfo.flatOverride < 0 ? rawAxisInfo.flat : axisInfo.flatOverride;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007186
7187 // Calculate scaling factors and limits.
7188 Axis axis;
7189 if (axisInfo.mode == AxisInfo::MODE_SPLIT) {
7190 float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue);
7191 float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007192 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, highScale,
7193 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7194 rawAxisInfo.resolution * scale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007195 } else if (isCenteredAxis(axisInfo.axis)) {
7196 float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
7197 float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale;
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007198 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, offset, scale,
7199 offset, -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7200 rawAxisInfo.resolution * scale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007201 } else {
7202 float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007203 axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, scale,
7204 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale,
7205 rawAxisInfo.resolution * scale);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007206 }
7207
7208 // To eliminate noise while the joystick is at rest, filter out small variations
7209 // in axis values up front.
7210 axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f;
7211
7212 mAxes.add(abs, axis);
7213 }
7214 }
7215
7216 // If there are too many axes, start dropping them.
7217 // Prefer to keep explicitly mapped axes.
7218 if (mAxes.size() > PointerCoords::MAX_AXES) {
Narayan Kamath37764c72014-03-27 14:21:09 +00007219 ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007220 getDeviceName().c_str(), mAxes.size(), PointerCoords::MAX_AXES);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007221 pruneAxes(true);
7222 pruneAxes(false);
7223 }
7224
7225 // Assign generic axis ids to remaining axes.
7226 int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1;
7227 size_t numAxes = mAxes.size();
7228 for (size_t i = 0; i < numAxes; i++) {
7229 Axis& axis = mAxes.editValueAt(i);
7230 if (axis.axisInfo.axis < 0) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007231 while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 &&
7232 haveAxis(nextGenericAxisId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007233 nextGenericAxisId += 1;
7234 }
7235
7236 if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) {
7237 axis.axisInfo.axis = nextGenericAxisId;
7238 nextGenericAxisId += 1;
7239 } else {
7240 ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids "
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007241 "have already been assigned to other axes.",
7242 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007243 mAxes.removeItemsAt(i--);
7244 numAxes -= 1;
7245 }
7246 }
7247 }
7248 }
7249}
7250
7251bool JoystickInputMapper::haveAxis(int32_t axisId) {
7252 size_t numAxes = mAxes.size();
7253 for (size_t i = 0; i < numAxes; i++) {
7254 const Axis& axis = mAxes.valueAt(i);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007255 if (axis.axisInfo.axis == axisId ||
7256 (axis.axisInfo.mode == AxisInfo::MODE_SPLIT && axis.axisInfo.highAxis == axisId)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007257 return true;
7258 }
7259 }
7260 return false;
7261}
7262
7263void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) {
7264 size_t i = mAxes.size();
7265 while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) {
7266 if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) {
7267 continue;
7268 }
7269 ALOGI("Discarding joystick '%s' axis %d because there are too many axes.",
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007270 getDeviceName().c_str(), mAxes.keyAt(i));
Michael Wrightd02c5b62014-02-10 15:10:22 -08007271 mAxes.removeItemsAt(i);
7272 }
7273}
7274
7275bool JoystickInputMapper::isCenteredAxis(int32_t axis) {
7276 switch (axis) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007277 case AMOTION_EVENT_AXIS_X:
7278 case AMOTION_EVENT_AXIS_Y:
7279 case AMOTION_EVENT_AXIS_Z:
7280 case AMOTION_EVENT_AXIS_RX:
7281 case AMOTION_EVENT_AXIS_RY:
7282 case AMOTION_EVENT_AXIS_RZ:
7283 case AMOTION_EVENT_AXIS_HAT_X:
7284 case AMOTION_EVENT_AXIS_HAT_Y:
7285 case AMOTION_EVENT_AXIS_ORIENTATION:
7286 case AMOTION_EVENT_AXIS_RUDDER:
7287 case AMOTION_EVENT_AXIS_WHEEL:
7288 return true;
7289 default:
7290 return false;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007291 }
7292}
7293
7294void JoystickInputMapper::reset(nsecs_t when) {
7295 // Recenter all axes.
7296 size_t numAxes = mAxes.size();
7297 for (size_t i = 0; i < numAxes; i++) {
7298 Axis& axis = mAxes.editValueAt(i);
7299 axis.resetValue();
7300 }
7301
7302 InputMapper::reset(when);
7303}
7304
7305void JoystickInputMapper::process(const RawEvent* rawEvent) {
7306 switch (rawEvent->type) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007307 case EV_ABS: {
7308 ssize_t index = mAxes.indexOfKey(rawEvent->code);
7309 if (index >= 0) {
7310 Axis& axis = mAxes.editValueAt(index);
7311 float newValue, highNewValue;
7312 switch (axis.axisInfo.mode) {
7313 case AxisInfo::MODE_INVERT:
7314 newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) * axis.scale +
7315 axis.offset;
7316 highNewValue = 0.0f;
7317 break;
7318 case AxisInfo::MODE_SPLIT:
7319 if (rawEvent->value < axis.axisInfo.splitValue) {
7320 newValue = (axis.axisInfo.splitValue - rawEvent->value) * axis.scale +
7321 axis.offset;
7322 highNewValue = 0.0f;
7323 } else if (rawEvent->value > axis.axisInfo.splitValue) {
7324 newValue = 0.0f;
7325 highNewValue =
7326 (rawEvent->value - axis.axisInfo.splitValue) * axis.highScale +
7327 axis.highOffset;
7328 } else {
7329 newValue = 0.0f;
7330 highNewValue = 0.0f;
7331 }
7332 break;
7333 default:
7334 newValue = rawEvent->value * axis.scale + axis.offset;
7335 highNewValue = 0.0f;
7336 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007337 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007338 axis.newValue = newValue;
7339 axis.highNewValue = highNewValue;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007340 }
Michael Wrightd02c5b62014-02-10 15:10:22 -08007341 break;
7342 }
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007343
7344 case EV_SYN:
7345 switch (rawEvent->code) {
7346 case SYN_REPORT:
7347 sync(rawEvent->when, false /*force*/);
7348 break;
7349 }
7350 break;
Michael Wrightd02c5b62014-02-10 15:10:22 -08007351 }
7352}
7353
7354void JoystickInputMapper::sync(nsecs_t when, bool force) {
7355 if (!filterAxes(force)) {
7356 return;
7357 }
7358
7359 int32_t metaState = mContext->getGlobalMetaState();
7360 int32_t buttonState = 0;
7361
7362 PointerProperties pointerProperties;
7363 pointerProperties.clear();
7364 pointerProperties.id = 0;
7365 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN;
7366
7367 PointerCoords pointerCoords;
7368 pointerCoords.clear();
7369
7370 size_t numAxes = mAxes.size();
7371 for (size_t i = 0; i < numAxes; i++) {
7372 const Axis& axis = mAxes.valueAt(i);
7373 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue);
7374 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
7375 setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis,
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007376 axis.highCurrentValue);
Michael Wrightd02c5b62014-02-10 15:10:22 -08007377 }
7378 }
7379
7380 // Moving a joystick axis should not wake the device because joysticks can
7381 // be fairly noisy even when not in use. On the other hand, pushing a gamepad
7382 // button will likely wake the device.
7383 // TODO: Use the input device configuration to control this behavior more finely.
7384 uint32_t policyFlags = 0;
7385
Prabir Pradhan42611e02018-11-27 14:04:02 -08007386 NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
Garfield Tan00f511d2019-06-12 16:55:40 -07007387 AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
7388 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState,
Atif Niyaz21da0ff2019-06-28 13:22:51 -07007389 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
7390 &pointerProperties, &pointerCoords, 0, 0,
Garfield Tan00f511d2019-06-12 16:55:40 -07007391 AMOTION_EVENT_INVALID_CURSOR_POSITION,
7392 AMOTION_EVENT_INVALID_CURSOR_POSITION, 0, /* videoFrames */ {});
Michael Wrightd02c5b62014-02-10 15:10:22 -08007393 getListener()->notifyMotion(&args);
7394}
7395
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007396void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis,
7397 float value) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007398 pointerCoords->setAxisValue(axis, value);
7399 /* In order to ease the transition for developers from using the old axes
7400 * to the newer, more semantically correct axes, we'll continue to produce
7401 * values for the old axes as mirrors of the value of their corresponding
7402 * new axes. */
7403 int32_t compatAxis = getCompatAxis(axis);
7404 if (compatAxis >= 0) {
7405 pointerCoords->setAxisValue(compatAxis, value);
7406 }
7407}
7408
7409bool JoystickInputMapper::filterAxes(bool force) {
7410 bool atLeastOneSignificantChange = force;
7411 size_t numAxes = mAxes.size();
7412 for (size_t i = 0; i < numAxes; i++) {
7413 Axis& axis = mAxes.editValueAt(i);
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007414 if (force ||
7415 hasValueChangedSignificantly(axis.filter, axis.newValue, axis.currentValue, axis.min,
7416 axis.max)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007417 axis.currentValue = axis.newValue;
7418 atLeastOneSignificantChange = true;
7419 }
7420 if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) {
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007421 if (force ||
7422 hasValueChangedSignificantly(axis.filter, axis.highNewValue, axis.highCurrentValue,
7423 axis.min, axis.max)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007424 axis.highCurrentValue = axis.highNewValue;
7425 atLeastOneSignificantChange = true;
7426 }
7427 }
7428 }
7429 return atLeastOneSignificantChange;
7430}
7431
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007432bool JoystickInputMapper::hasValueChangedSignificantly(float filter, float newValue,
7433 float currentValue, float min, float max) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007434 if (newValue != currentValue) {
7435 // Filter out small changes in value unless the value is converging on the axis
7436 // bounds or center point. This is intended to reduce the amount of information
7437 // sent to applications by particularly noisy joysticks (such as PS3).
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007438 if (fabs(newValue - currentValue) > filter ||
7439 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) ||
7440 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) ||
7441 hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007442 return true;
7443 }
7444 }
7445 return false;
7446}
7447
Prabir Pradhanda7c00c2019-08-29 14:12:42 -07007448bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange(float filter, float newValue,
7449 float currentValue,
7450 float thresholdValue) {
Michael Wrightd02c5b62014-02-10 15:10:22 -08007451 float newDistance = fabs(newValue - thresholdValue);
7452 if (newDistance < filter) {
7453 float oldDistance = fabs(currentValue - thresholdValue);
7454 if (newDistance < oldDistance) {
7455 return true;
7456 }
7457 }
7458 return false;
7459}
7460
7461} // namespace android